<?php
namespace app\model;
/** * Author: cbw * Desc: 易宣短信服务 * Time: 2022/12/6 13:52 * Email: 17854288794@163.com */class Sms{    //极验id    private static $gt_id = '55703a84daadee29886a40b23f4b16ff';    //极验key    private static $gt_key = '2f74a615d144e25c1b541a85f6c3d44c';    //短信发送接口    private static $message_url = 'https://tectapi.geetest.com/v2/message';    //短信报告查询接口    private static $message_report = 'https://tectapi.geetest.com/v2/message_report';    //微信生成短链    private static $url_link = 'https://api.weixin.qq.com/wxa/generate_urllink?access_token=';    //当前短信服务商    private static $server_code = 'gt'; //gt 极验  alisms  阿里短信    //ali acc参数 参数禁止修改 如需修改请测试所有流程中的权限是否正确    private static $access_key_id = 'LTAI5tRW9DudoNKfebNR6VBq';    private static $access_key_secret = 'fvWg6tJJJelOEL9hI4MsqmOodMCyT3';    //联麓参数    private static $ll_notify_appid = '10011689591379945';//通知短信appid    private static $ll_notify_appkey = 'ebe81ca19489470e8c748a0699685b62';//通知短信appkey    private static $ll_sales_appid = '10021689591380645';//营销短信appid    private static $ll_sales_appkey = '689bf74d31a946968be5fbfac1300caf';//营销短信appkey    private static $ll_mchid = '1030903';    private static $ll_signType = 'MD5';    private static $ll_version = '1.1.0';    public static function CheckAndSendSms($key, $system, $config, $themeid, $record = [], $insert_data = [])    {        //判断61领泽，不可走极验短信。        if (DOMAIN1 == "www.yixuan.net") {            $temp_id = self::llSmsTemplateArr($system, $config, $key);            if(empty($temp_id)){                return false;            }        }        if (!db_tableexists(t_sms_config)) {            return;        }        $has_sms_config = db_get(t_sms_config, ['themeid' => $themeid, 'module_name' => MODULE_NAME]);        if (!$has_sms_config && !$config['open_yx_sms']) {//            yxlog('短信-内置未开启'.$key,'短信发送失败');            return false;        }        if ($has_sms_config && !$has_sms_config['open_yx_sms']) {//            yxlog('短信-配置未开启','短信发送失败');            return false;        }        if (!$config['sms_' . $key] && !$has_sms_config['sms_' . $key]) {            //未开启此配置            return false;        }        if (db_tableexists(t_sms_config)) {            $config = array_merge($config, $has_sms_config);        }        if (empty($system)) {            $setting = db_find("SELECT * FROM " . tablename('uni_account_modules') . " WHERE module=:module  order by uniacid asc", array(':module' => MODULE_NAME));            $system = !empty($setting['settings']) ? xunserializer($setting['settings']) : array();        }        $key_index = $config['sms_' . $key];        switch ($key) {            case in_array($key, ['fenxiao01', 'fenxiao02', 'fenxiao03', 'comm_agent', 'fenxiao06']):                $sendData = [                    'uid' => $insert_data['uid'],                    'arguments' => [                        'friend_name' => $record['username'],                        'money' => $insert_data['fee'],                    ],                ];                break;            case in_array($key, ['fenxiao05', 'fenxiao08']):                $sendData = [                    'uid' => $insert_data['uid'],                    'arguments' => [                        'money' => $insert_data['fee'],                    ],                ];                $key_index = 0;                break;            case 'lottery_new':                $sendData = [                    'uid' => $record['uid'],                    'arguments' => [                        'num' => $insert_data['num'],                    ],                ];                break;            case 'self_buy':                $worker_info = Worker::getThemeWorkerByUid($record['workerid'], $themeid, 1);                if (!empty($worker_info['mobile'])) {                    $work_phone = $worker_info['mobile'];                } else {                    $theme = Theme::getThemeById($themeid);                    $work_phone = $theme['mobile'];                }                $sendData = [                    'uid' => $record['uid'],                    'arguments' => [                        'work_phone' => $work_phone,                    ],                ];                break;            case in_array($key, ['friend_newfans', 'friend_buy']):                $uid = $record['fromuid'];                if ($key == 'friend_newfans') {                    $relation_uid = db_get(t_relation, ['themeid' => $themeid, 'uid' => $record['uid']])['parentid'];                    if ($relation_uid) {                        $uid = $relation_uid;                    }                }                $sendData = [                    'uid' => $uid,                    'arguments' => [                        'friend_name' => !empty($record['username']) ? $record['username'] : $record['nickname'],                    ],                ];                break;            case in_array($key, ['bargain_help', 'bargain_success', 'bargain_fail']):                if ($key == 'bargain_help') {                    if (Bargain::getBargainType($config) == 'limit_user') {                        $flag = Bargain::getBargainCountByFromUidAndBeId($themeid, $record['be_id'], $record['uid']);                        $need_num = $config['bargain_friendnum'] - $flag - 1;                        $key_index = 0;                    } else {                        $key_index = 1;                    }                }                $fans = Fans::getById($insert_data['uid'], $themeid);                $sendData = [                    'uid' => $record['uid'],                    'arguments' => [                        'friend_name' => !empty($fans['username']) ? $fans['username'] : $fans['nickname'],                        'money' => $insert_data['sub_amount'],                        'need_num' => $need_num,                    ],                ];                break;            case in_array($key, ['friend_help', 'friend_help_success', 'mystery_boxes_new']):                if ($key == 'mystery_boxes_new') {                    $key_index = $record['success_mode'];                }                $sendData = [                    'uid' => $insert_data['fromuid'],                    'arguments' => [                        'friend_name' => !empty($record['username']) ? $record['username'] : $record['nickname'],                    ],                ];                break;            case in_array($key, ['pintuan_success', 'pintuan_new']):                if ($key == 'pintuan_new') {                    $num = Record::getAttendDetailNumByPId($config, $record['pid']) + 1;                }                $sendData = [                    'uid' => $insert_data['uid'],                    'arguments' => [                        'friend_name' => $record['username'],                        'num' => $num,                    ],                ];                break;            case 'presale':                $key_index -= 1;                $sendData = [                    'uid' => $insert_data['uid'],                    'arguments' => [                        'username' => $insert_data['username'],                    ],                ];                break;            case 'currency':                $key_index -= 1;                $sendData = [                    'uid' => $insert_data['uid'],                    'arguments' => [                        'username' => $insert_data['username'],                    ],                ];                break;        }        //判断员工是否可以到短信通知        if (empty($config['sms_worker'])) {            $isworker = Worker::getThemeWorkerByUid($sendData['uid'], $themeid, 1);            if ($isworker) {                return false;            }        }        return Sms::sendSms($system, $themeid, $sendData['uid'], $key, $key_index, $sendData['arguments']);    }    public static function sendSms($system, $themeid, $phone, $key, $key_index = 0, $arguments)    {        $res = ['themeid' => $themeid, 'phone' => $phone, 'key' => $key, 'key_index' => $key_index, 'arguments' => $arguments];        yxlog($res, '短信发送参数');        if (!$themeid) {            $res = ['status' => 0, 'msg' => '活动id缺失', 'key' => $key, 'key_index' => $key_index];            yxlog($res, '短信发送失败');            return $res;        }        if (!$phone) {            $res = ['status' => 0, 'msg' => '手机号或uid缺失', 'key' => $key, 'key_index' => $key_index];            yxlog($res, '短信发送失败');            return $res;        }        if (!is_array($phone)) {            $phone = [$phone];        }        if (!$key) {            $res = ['status' => 0, 'msg' => '短信通知类型缺失', 'key' => $key, 'key_index' => $key_index];            yxlog($res, '短信发送失败');            return $res;        }        $config = Theme::getConfig($themeid);        if (db_tableexists(t_sms_config)) {            $has_sms_config = db_get(t_sms_config, ['themeid' => $themeid, 'module_name' => MODULE_NAME]);            $config = array_merge($config, $has_sms_config);        }        $temp_item = self::getSmsTemplateArr($system, $config, $key, $key_index)['item'];        $temp_id = self::getSmsTemplateArr($system, $config, $key, $key_index)['temp_id'];        if (!$temp_item) {            $res = ['status' => 0, 'msg' => '短信模版不存在', 'key' => $key, 'key_index' => $key_index];            yxlog($res, '短信发送失败');            return $res;        } else {            if ($temp_item && $temp_item['arguments'] && !$arguments) {                $res = ['status' => 0, 'msg' => '短信模版参数缺失', 'key' => $key, 'key_index' => $key_index, 'arguments' => $arguments];                yxlog($res, '短信发送失败');                return $res;            }        }        $batch_limit = 50;        $type = $key;// 默认 为空        $theme = Theme::getThemeById($themeid);        $auth = self::auth(self::$gt_id, self::$gt_key);        if (count($phone) > 1) {            //批量            $phones = array_unique($phone);//数组去重            //判断调用极验 还是阿里云            if (self::$server_code != 'gt') {                $alisms_send_total = 0;                //阿里云                $phone_arr = [];                $uid_arr = [];                $signName = [];                $send_sms_flag_arr = [];                $template_params_arr = [];            }            $queue_fileds = 'uid,mobile,type,status,templateId,templateKey,content,des,themeid';            $queue_vals = "";            foreach ($phones as $k => $phone) {                //不传递uid  通过手机号去fans表匹配                if (mb_strlen($phone) == 11) {                    //mobile                    $uid = 0;                    $fans = [];                    if (self::$server_code != 'gt') {                        array_push($uid_arr, $uid);                    }                } else {                    //uid                    $where = ['themeid' => $themeid, 'uid' => $phone];                    $fans = db_get(t_fans, $where);                    if ($fans && $fans['mobile']) {                        $uid = $fans['uid'];                        $phone = $fans['mobile'];                        if (self::$server_code != 'gt') {                            array_push($uid_arr, $uid);                        }                    } else {                        $fans = [];                        $res = ['status' => 0, 'msg' => '粉丝信息不存在:uid' . $phone];                        yxlog($res, '短信发送失败');                        continue;                    }                }                $item_arguments = self::formatArguments($arguments[$k], $temp_item, $theme, $system, $fans, $config);                if (self::$server_code != 'gt') {                    if ($alisms_send_total < $batch_limit) {                        $is_auto = self::getSmsTemplateArr($system, $config, $key, $key_index)['item']['is_auto'];                        $sms_length = (int)mb_strlen(self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments), 'UTF8');                        //判断能余额能否发短信                        if ($sms_length > 350) {                            $res = ['status' => 0, 'msg' => '短信长度过长,超过350个字符'];                            yxlog($res, '短信批量发送失败');                            return $res;                        }                        $send_sms_flag = self::getSmsContentFlag($sms_length);                        $can_send_sms = self::checkCanSendSms($themeid, $send_sms_flag);                        if (!$can_send_sms) {                            //余额不足仅记录自动发送                            if ($is_auto) {                                //插入队列                                $data = [                                    'uid' => $uid,                                    'mobile' => $phone,                                    'type' => $type,                                    'status' => 1,                                    'templateId' => $temp_id,                                    'templateKey' => $key_index,                                    'content' => $temp_item['temp_content'],                                    'des' => json_encode($arguments),                                    'themeid' => $themeid                                ];                                self::addSmsQueue($data);                            }                            $res = ['status' => 0, 'msg' => '活动后台短信账户余额不足,无法抵扣短信费用'];                            yxlog($res, '短信发送失败');                            return $res;                            die();                        }                        //判断用户指定时间内访问次数 是否达到未访问阀值                        $validate_activity_user = self::validateUserIsActivity($themeid, $uid, $config);                        if (!$validate_activity_user) {                            //时间内 用户未被激活 发送失败                            //记录发送失败日志                            $data = [                                'uid' => $uid,                                'mobile' => $phone,                                'type' => $type,                                'status' => 3,                                'templateId' => $temp_id,                                'templateKey' => $key_index,                                'tradeId' => isset($response['trade_id']) ? $response['trade_id'] : '',                                'trade_status' => 'ERROR',                                'content' => self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments),                                'sms_num' => $send_sms_flag,                                'des' => '静默用户',                                'themeid' => $themeid                            ];                            self::addSendLog($data);                            $res = ['status' => 1, 'msg' => '发送失败，静默用户;phone:' . $phone];                            yxlog($res, '短信发送失败');                            continue;                        }                        array_push($phone_arr, $phone);                        array_push($send_sms_flag_arr, $send_sms_flag);                        array_push($signName, $temp_item['SignName']);                        array_push($template_params_arr, $arguments[$k]);                        $alisms_send_total += 1;                    } else {                        $temp_queue_vals = "(";                        $temp_queue_vals .= "'" . $uid . "',";                        $temp_queue_vals .= "'" . $phone . "',";                        $temp_queue_vals .= "'" . $type . "',";                        $temp_queue_vals .= "'1',";                        $temp_queue_vals .= "'" . $temp_id . "',";                        $temp_queue_vals .= "'" . $key_index . "',";                        $temp_queue_vals .= "'" . $temp_item['temp_content'] . "',";                        $temp_queue_vals .= "'" . json_encode($item_arguments) . "',";                        $temp_queue_vals .= "'" . $themeid . "'),";                        $queue_vals .= $temp_queue_vals;                    }                } else {                    $temp_queue_vals = "(";                    $temp_queue_vals .= "'" . $uid . "',";                    $temp_queue_vals .= "'" . $phone . "',";                    $temp_queue_vals .= "'" . $type . "',";                    $temp_queue_vals .= "'1',";                    $temp_queue_vals .= "'" . $temp_id . "',";                    $temp_queue_vals .= "'" . $key_index . "',";                    $temp_queue_vals .= "'" . $temp_item['temp_content'] . "',";                    $temp_queue_vals .= "'" . json_encode($item_arguments) . "',";                    $temp_queue_vals .= "'" . $themeid . "'),";                    $queue_vals .= $temp_queue_vals;                }            }            $queue_vals = rtrim($queue_vals, ',');            if ($queue_vals) {                self::batchInsert(tablename(t_sms_wait_send_queue), $queue_fileds, $queue_vals);            }            if ($phone_arr && $signName && $template_params_arr && $alisms_send_total > 0) {                //阿里短信批量发出 50条                $response = self::sendBatchSms($phone_arr, $signName, $temp_id, $template_params_arr);                if ($response['status'] != 200) {                    //批量失败压入队列                    $error = self::getErrorMessage($response['status']);                    $res = ['status' => 0, 'msg' => $response['status'] . '-' . $error];                    $queue_fileds = 'uid,mobile,type,status,templateId,templateKey,content,des,themeid';                    $log_fileds = $queue_fileds . 'tradeId,trade_status,sms_num';                    $queue_vals = $log_vals = "";                    foreach ($phone_arr as $k1 => $v1) {                        //队列                        $temp_vals = " (";                        $temp_vals .= "'" . $uid_arr[$k1] . "',";                        $temp_vals .= "'" . $v1 . "',";                        $temp_vals .= "'" . $type . "',";                        $temp_vals .= "'1',";                        $temp_vals .= "'" . $temp_id . "',";                        $temp_vals .= "'" . $key_index . "',";                        $temp_vals .= "'" . $temp_item['temp_content'] . "',";                        $temp_vals .= "'" . json_encode($template_params_arr[$k1]) . "',";                        $temp_vals .= "'" . $themeid . "'),";                        $queue_vals .= $temp_vals;                        //记录发送失败日志                        $temp_vals1 = " (";                        $temp_vals1 .= "'" . $uid_arr[$k1] . "',";                        $temp_vals1 .= "'" . $v1 . "',";                        $temp_vals1 .= "'" . $type . "',";                        $temp_vals1 .= "'2',";                        $temp_vals1 .= "'" . $temp_id . "',";                        $temp_vals1 .= "'" . $key_index . "',";                        $temp_vals1 .= "'" . self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $template_params_arr[$k1]) . "',";                        $temp_vals1 .= "'" . $response['status'] . '-' . $error . "',";                        $temp_vals1 .= "'" . $themeid . "',";                        $temp_vals1 .= "'" . $response['trade_id'] . "',";                        $temp_vals1 .= "'ERROR',";                        $temp_vals1 .= "'" . $send_sms_flag_arr[$k1] . "'),";                        $log_vals .= $temp_vals1;                    }                    $queue_vals = rtrim($queue_vals, ',');                    $log_vals = rtrim($log_vals, ',');                    $res = self::batchInsert(tablename(t_sms_wait_send_queue), $queue_fileds, $queue_vals);                    $res = self::batchInsert(tablename(t_sms_send_log), $log_fileds, $log_vals);                } else {                    $fileds = 'uid,mobile,type,status,templateId,templateKey,tradeId,content,sms_num,des,themeid';                    $fileds1 = $fileds . ',trade_status';                    $format_values = $format_values1 = " ";                    $item_arguments = self::formatArguments($arguments[$k], $temp_item, $theme, $system, $fans, $config);                    foreach ($phone_arr as $k1 => $v1) {                        $temp_vals = " (";                        $temp_vals .= "'" . $uid_arr[$k1] . "',";                        $temp_vals .= "'" . $v1 . "',";                        $temp_vals .= "'" . $type . "',";                        $temp_vals .= "'1',";                        $temp_vals .= "'" . $temp_id . "',";                        $temp_vals .= "'" . $key_index . "',";                        $temp_vals .= "'" . $response['trade_id'] . "',";                        $temp_vals .= "'" . self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $template_params_arr[$k1]) . "',";                        $temp_vals .= "'" . $send_sms_flag_arr[$k1] . "',";                        $temp_vals .= "'" . json_encode($item_arguments) . "',";                        $temp_vals1 = $temp_vals . "'" . $themeid . "'," . "'UNKNOW'),";                        $format_values1 .= $temp_vals1;                        $temp_vals .= "'" . $themeid . "'),";                        $format_values .= $temp_vals;                    }                    $format_values = rtrim($format_values, ',');                    $format_values1 = rtrim($format_values1, ',');                    $res = self::batchInsert(tablename(t_sms_send_flag), $fileds, $format_values);                    $res = self::batchInsert(tablename(t_sms_send_log), $fileds1, $format_values1);                }            }            return ['status' => 1, 'msg' => '批量短信加入队列成功'];        } else {            //单个发送            $phone = (string)$phone[0];            //不传递uid  通过手机号去fans表匹配            if (mb_strlen($phone) == 11) {                //mobile                $uid = 0;                $fans = [];            } else {                //uid                $uid = $phone;                $where = ['themeid' => $themeid, 'uid' => $uid];                $fans = db_get(t_fans, $where);                if ($fans && $fans['mobile']) {                    $uid = $fans['uid'];                    $phone = $fans['mobile'];                } else {                    $fans = [];                    $res = ['status' => 0, 'msg' => '粉丝信息不存在'];                    yxlog($res, '短信发送失败uid' . $uid);                    return $res;                }            }            $valid_sms = self::validateSendRule($themeid, $phone);            if (!$valid_sms){                yxlog('手机号频率超过', '短信发送失败');                //插入队列                $data = [                    'uid'=>$uid,                    'mobile'=>$phone,                    'type'=>$type,                    'status'=>1,                    'templateId'=>$temp_id,                    'templateKey'=>$key_index,                    'des'=>json_encode($arguments),                    'themeid'=>$themeid                ];                if (self::$server_code == 'll') {                    $data['content'] = self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments);                }else{                    $data['content'] = $temp_item['temp_content'];                }                self::addSmsQueue($data);                return ['status'=>0,'msg'=>'手机号发送频率受限'];            }            $arguments = self::formatArguments($arguments, $temp_item, $theme, $system, $fans, $config);            $is_auto = self::getSmsTemplateArr($system, $config, $key, $key_index)['item']['is_auto'];            $sms_length = (int)mb_strlen(self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments), 'UTF8');            if ($sms_length > 350) {                $res = ['status' => 0, 'msg' => '短信长度过长,超过350个字符'];                yxlog($res, '短信发送失败');                return $res;            }            //判断能否余额是否能抵扣短信费用            $send_sms_flag = self::getSmsContentFlag($sms_length);            $can_send_sms = self::checkCanSendSms($themeid, $send_sms_flag);            if (!$can_send_sms){                //余额不足仅记录自动发送                if ($is_auto){                    //插入队列                    $data = [                        'uid'=>$uid,                        'mobile'=>$phone,                        'type'=>$type,                        'status'=>1,                        'templateId'=>$temp_id,                          'server_code' => self::$server_code,                        'templateKey'=>$key_index,                        'des'=>json_encode($arguments),                        'themeid'=>$themeid                    ];                        if (self::$server_code == 'll') {                            $data['content'] = self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments);                        }else{                            $data['content'] = $temp_item['temp_content'];                        }                    self::addSmsQueue($data);                }                $res = ['status'=>0,'msg'=>'活动后台短信账户余额不足,无法抵扣短信费用'];                yxlog($res,'短信发送失败');                return $res;                die();            }            //判断小时、日发送上限是否达到            $hour_limit = self::getUsedSmsTotal($themeid, 'hour');            if ($hour_limit > $config['sms_hour_max']) {                yxlog('达到每小时发放阀值', '短信发送受限');//                self::addSendLog($data);                //压入队列                $data = [                    'uid' => $uid,                    'mobile' => $phone,                    'type' => $type,                    'status' => 5,                    'templateId' => $temp_id,                    'server_code' => self::$server_code,                    'templateKey' => $key_index,                    'des' => json_encode($arguments),                    'themeid' => $themeid                ];                if (self::$server_code == 'll') {                    $data['content'] = self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments);                }else{                    $data['content'] = $temp_item['temp_content'];                }                self::addSmsQueue($data);                return;            } else {                $day_limit = self::getUsedSmsTotal($themeid, 'day');                if ($day_limit > $config['sms_day_max']) {                    yxlog('达到每日发放阀值', '短信发送受限');                    //压入队列                    $data = [                        'uid' => $uid,                        'mobile' => $phone,                        'type' => $type,                        'status' => 5,                        'templateId' => $temp_id,                        'server_code' => self::$server_code,                        'templateKey' => $key_index,                        'des' => json_encode($arguments),                        'themeid' => $themeid                    ];                    if (self::$server_code == 'll') {                        $data['content'] = self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments);                    }else{                        $data['content'] = $temp_item['temp_content'];                    }                    self::addSmsQueue($data);                    return;                }            }            //判断用户指定时间内访问次数 是否达到未访问阀值            $validate_activity_user = self::validateUserIsActivity($themeid, $uid, $config);            if (!$validate_activity_user) {                //时间内 用户未被激活 发送失败                //记录发送失败日志                $data = [                    'uid' => $uid,                    'mobile' => $phone,                    'type' => $type,                    'status' => 3,                    'templateId' => $temp_id,                    'templateKey' => $key_index,                    'tradeId' => isset($response['trade_id']) ? $response['trade_id'] : '',                    'trade_status' => 'ERROR',                    'sms_num' => $send_sms_flag,                    'des' => '静默用户',                    'themeid' => $themeid                ];                if (self::$server_code == 'll') {                    $data['content'] = self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments);                }else{                    $data['content'] = $temp_item['temp_content'];                }                self::addSendLog($data);                $res = ['status' => 0, 'msg' => '发送失败,静默用户'];                return $res;            }            //判断调用联麓、极验 还是阿里云            if (self::$server_code == 'll') {                $mobile_arr[0] = $phone;                $template_code = $temp_id;                $template_params_arr = [];                foreach ($arguments as $key => $value) {                    array_push($template_params_arr, $value);                }                $response = Sms::llSmsSend($mobile_arr, $template_code, $template_params_arr, '','sales');                $response['trade_id'] = $response['data']['taskId'];            } elseif (self::$server_code == 'gt') {                $post_data = [                    'phone' => $phone,                    'modeId' => $temp_id                ];                if ($temp_item['arguments']) {                    $post_data['arguments'] = $arguments;                }                $response = self::request_data(self::$message_url, $post_data, 'POST', $auth);            } else {                $signName = $temp_item['SignName'];                $temp_code = $temp_id;                $template_params_arr = $arguments;                $response = self::aliSendSms($phone, $signName, $temp_code, $template_params_arr);            }            if ($response['status'] != 200) {                $error = self::getErrorMessage($response['status']);                $res = ['status' => 0, 'msg' => $response['status'] . '-' . $error];                //记录发送失败日志//                $data = [//                    'uid' => $uid,//                    'mobile' => $phone,//                    'type' => $type,//                    'status' => 2,//                    'templateId' => $temp_id,//                    'templateKey' => $key_index,//                    'tradeId' => isset($response['trade_id']) ? $response['trade_id'] : '',//                    'trade_status' => 'ERROR',//                    'server_code' => self::$server_code,//                    'content' => self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments),//                    'sms_num' => $send_sms_flag,//                    'des' => $response['status'] . '-' . $error,//                    'themeid' => $themeid//                ];//                self::addSendLog($data);                //插入队列                $data = [                    'uid' => $uid,                    'mobile' => $phone,                    'type' => $type,                    'status' => 1,                    'templateId' => $temp_id,                    'templateKey' => $key_index,                    'server_code' => self::$server_code,                    'des' => json_encode($arguments),                    'themeid' => $themeid                ];                if (self::$server_code == 'll') {                    $data['content'] = self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments);                }else{                    $data['content'] = $temp_item['temp_content'];                }                self::addSmsQueue($data);            } else {                //发送成功 增加发送记录                $data = [                    'uid' => $uid,                    'mobile' => $phone,                    'type' => $type,                    'status' => 1,                    'templateId' => $temp_id,                    'templateKey' => $key_index,                    'tradeId' => isset($response['trade_id']) ? $response['trade_id'] : '',                    'content' => self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments),                    'sms_num' => $send_sms_flag,                    'des' => json_encode($arguments),                    'themeid' => $themeid                ];                $data['trade_status'] = 'UNKNOW';                //记录发送成功日志                self::addSendLog($data);                unset($data['trade_status']);                self::addSmsSendFlag($data);                $res = ['status' => 1, 'msg' => '发送成功'];            }            return $res;        }    }    //请求    /**     * Desc:格式化模版信息     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 17:48     * @param string $temp_id     * @return array|array[]     */    public static function getSmsTemplateArr($system, $config, $key = 'all', $key_index = 0, $demo = false, $get_key_arr = false)    {        //此处为判断是否使用联麓        $llSmsTemplateArr = self::llSmsTemplateArr($system, $config, $key, $key_index, $demo, $get_key_arr);        if (!empty($llSmsTemplateArr)) {            return $llSmsTemplateArr;        }        $key_arr = [            'bargain_help' =>                [                    [                        'name' => '帮砍提醒-剩余人数', 'temp_content' => '#username#，刚刚好友#friend_name#帮您砍了一刀，还需#need_num#人即可砍至最底价。详情 y0x.cn/#url_code#',                        'arguments' => [                            ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'need_num', 'desc' => '几人', 'demo' => '1'],                            ['code' => 'url_code', 'desc' => '活动code', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                        'page' => '',                        'SignName' => '',                    ],                    [                        'name' => '帮砍提醒-剩余金额', 'temp_content' => '#username#，刚刚好友#friend_name#帮您砍掉#money#元。详情 y0x.cn/#url_code#',                        'arguments' => [                            ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '金额', 'demo' => '10.00'],                            ['code' => 'url_code', 'desc' => '活动code', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                        'page' => '',                        'SignName' => '',                    ]                ],            'bargain_success' =>                [                    [                        'name' => '砍价成功', 'temp_content' => '#username#，刚刚好友#friend_name#帮您砍掉#money#元，恭喜您已砍至最底价。详情 y0x.cn/#url_code#',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '金额', 'demo' => '10.00'],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'bargain_fail' =>                [                    [                        'name' => '砍价失败', 'temp_content' => '#username#，很遗憾，您的砍价未完成，您可以重新发起砍价。详情 y0x.cn/#url_code#',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao01' =>                [                    [                        'name' => '一级分销1', 'temp_content' => '#username#，刚刚#friend_name#通过您的推荐下单，本次获得#money#元。详情 y0x.cn/#url_code#',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao02' =>                [                    [                        'name' => '二级分销1', 'temp_content' => '#username#，您的好友#friend_name#推荐1人下单，您获得#money#元。详情 y0x.cn/#url_code#',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao03' =>                [                    [                        'name' => '三级分销1', 'temp_content' => '#username#，您的好友#friend_name#推荐1人下单，您获得#money#元。详情 y0x.cn/#url_code#',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao05' =>                [                    [                        'name' => '阅读红包', 'temp_content' => '#username#，新好友访问您的专属链接，您获得#money#元。详情 y0x.cn/#url_code#',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao06' => [                [                    'name' => '员工提成', 'temp_content' => '#username#，您的客户#friend_name#已下单，本次获得#money#元。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'fenxiao08' => [                [                    'name' => '额外红包', 'temp_content' => '#username#，管理员送您红包#money#元，已发放到您的微信零钱中。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'comm_agent' => [                [                    'name' => '代理提成', 'temp_content' => '#username#，您的客户#friend_name#已下单，本次获得#money#元。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'self_buy' => [                [                    'name' => '客户支付成功', 'temp_content' => '#username#，您已支付成功，#desc#，有任何疑问请致电#work_phone#。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'desc', 'desc' => '描述', 'demo' => $config['sms_self_buy_tips']],                        ['code' => 'work_phone', 'desc' => '联系方式', 'demo' => '13123452345'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'friend_buy' => [                [                    'name' => '好友购买', 'temp_content' => '#username#，刚刚好友#friend_name#通过您的推荐下单。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'friend_help' => [                [                    'name' => '好友助力', 'temp_content' => '#username#，好友#friend_name#刚刚帮您成功助力。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'friend_help_success' => [                [                    'name' => '好友助力成功', 'temp_content' => '#username#，好友#friend_name#刚刚帮您成功助力，恭喜您完成助力。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'friend_newfans' => [                [                    'name' => '好友到访', 'temp_content' => '#username#，刚刚好友#friend_name#访问过您的分享。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'lottery_new' => [                [                    'name' => '抽奖机会增加', 'temp_content' => '#username#，恭喜您，#desc#获得#num#次机会，快去使用吧。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'desc', 'desc' => '机会来源', 'demo' => '通过转发'],                        ['code' => 'num', 'desc' => '机会次数', 'demo' => '1'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'mystery_boxes_new' => [                [                    'name' => '新盲盒拼团成功可拆', 'temp_content' => '#username#，刚刚#friend_name#加入您的团，恭喜您拼团成功，可以拆盲盒啦。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '新盲盒助力成功可拆', 'temp_content' => '#username#，好友#friend_name#刚刚帮您成功助力，恭喜您可以拆盲盒啦。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => ''],                    ],                    'is_auto' => true,                ],            ],            'pintuan_new' => [                [                    'name' => '新成员通知', 'temp_content' => '#username#，刚刚#friend_name#加入您的团，您的团已有#num#人。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友名称', 'demo' => '王小四'],                        ['code' => 'num', 'desc' => '人数', 'demo' => '1'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => ''],                    ],                    'is_auto' => true,                ]            ],            'pintuan_success' => [                [                    'name' => '拼团成功', 'temp_content' => '#username#，刚刚#friend_name#加入您的团，恭喜您组团成功。详情 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => ''],                    ],                    'is_auto' => true,                ]            ],            'presale' => [                [                    'name' => '补款通知', 'temp_content' => '#username#，您抢购的商品，开始补款啦，立即补款 y0x.cn/#url_code#',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '新品开售', 'temp_content' => '#username#，新品已上线，立即抢购 y0x.cn/#url_code# 拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '大卡开售', 'temp_content' => '#username#，您预约的活动开始啦，速速抢购 y0x.cn/#url_code# 拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],            ],        ];        if (self::$server_code == 'gt') {            //极验            $oem_arr = [                '易宣' => [                    'bargain_help' => ['2022122714425163134', '2022122714433958397'],//砍价 人数 金额                    'bargain_success' => ['2022122714444329883'],//砍价成功                    'bargain_fail' => ['2022122714452349354'],//砍价失败                    'fenxiao01' => ['2022120913374129217'],//一级分销  订单提醒6                    'fenxiao02' => ['2022120913452061313'],//二级分销  订单提醒7                    'fenxiao03' => ['2022120913452061313'],//三级分销  订单提醒7                    'fenxiao05' => ['2022120914432564459'],//阅读红包  订单提醒9                    'fenxiao06' => ['2022122808454566362'],//员工提成                    'fenxiao08' => ['2022122713293984574'],//额外红包                    'comm_agent' => ['2022122808454566362'],//代理提成                    'self_buy' => ['2022122715181516545'],//客服支付成功                    'friend_buy' => ['2022122715190902339'],//好友购买                    'friend_help' => ['2022122714461787558'],//好友助力                    'friend_help_success' => ['2022122715162574104'],//好友助力成功                    'friend_newfans' => ['2022122715194645507'],//好友到访                    'lottery_new' => ['2022122715210277936'],//抽奖机会增加                    'mystery_boxes_new' => ['2022122715232547777', '2022122715241067038'],//盲盒  拼团 助力                    'pintuan_new' => ['2022122715245101741'],//新成员通知                    'pintuan_success' => ['2022122715253316335'],//拼团成功                    'presale' => ['2022122715263330423', '2022122715275188225', '2022122715284091053'],//预售 补款 新品 大卡                ],//                '金策' => [],//                '飞驰' => [],//                '联登' => [],//                '领泽' => [],            ];        } else {            //阿里云            $oem_arr = [                '易宣' => [                    'bargain_help' => [''],                    'bargain_success' => [''],                    'bargain_fail' => [''],                    'fenxiao01' => ['2022120913374129217'],//订单提醒6                    'fenxiao02' => ['2022120913452061313'],//订单提醒7                    'fenxiao03' => ['2022120913452061313'],//订单提醒7                    'fenxiao05' => ['2022120914432564459'],//订单提醒9                    'fenxiao06' => [''],                    'fenxiao08' => [''],                    'friend_buy' => [''],                    'friend_help' => [''],                    'friend_newfans' => [''],                    'lottery_new' => [''],                    'mystery_boxes_new' => [''],                    'pintuan_new' => [''],                    'pintuan_success' => [''],                    'presale' => [''],                    'worker' => [''],                    'test' => ['SMS_169870437'],//测试短信 支付成功                ],                '金策' => [],                '飞驰' => [],                '联登' => [],                '领泽' => [],            ];        }        if ($get_key_arr) {            return $key_arr;        }        $oem_str = self::getSignature($system);        if (!array_key_exists($oem_str, $oem_arr)) {            $oem_str = '易宣';        }        if ($key == 'all') {            $key_arr['diy'] = [                [                    'name' => '自定义模版', 'temp_content' => '',                    'arguments' => [                    ],                    'is_auto' => true,                ]            ];            return $key_arr;        }        if ($key_index && !$oem_arr[$oem_str][$key][$key_index]) {            $key_index = 0;        }        $key_temp_id = $oem_arr[$oem_str][$key][$key_index];        if (!$key_temp_id && !$demo) {            return [];        }        $temp_item = $key_arr[$key][$key_index];        if (!$temp_item) {            return [];        }        if ($demo) {            $item_content = $temp_item['temp_content'];            $item_arguments = $temp_item['arguments'];            foreach ($item_arguments as $k => $v) {                $tmp_code = '#' . $v['code'] . '#';                $demo_val = $v['demo'];                if ($v['code'] == 'url_code') {                    $demo_val = 'x48MDn';                }                $item_content = str_replace($tmp_code, $demo_val, $item_content);            }            return $item_content;        } else {            return ['temp_id' => $key_temp_id, 'item' => $temp_item];        }    }    /**     * Desc:联麓预置短信模板ID     * User: mf     * Email:732220552@qq.com     * Time: 2023/7/19 14:05     */    public static function llSmsTemplateArr($system, $config, $key = '', $key_index = 0, $demo = false, $get_key_arr = false)    {        $key_arr = [            'fenxiao01' =>                [                    [                        'name' => '一级分销1', 'temp_content' => '#username#，刚刚#friend_name#通过您的推荐下单，本次获得#money#元。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao02' =>                [                    [                        'name' => '二级分销1', 'temp_content' => '#username#，您的好友#friend_name#推荐1人下单，您获得#money#元。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao03' =>                [                    [                        'name' => '三级分销1', 'temp_content' => '#username#，您的好友#friend_name#推荐1人下单，您获得#money#元。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao05' =>                [                    [                        'name' => '阅读红包', 'temp_content' => '#username#，新好友访问您的专属链接，您获得#money#元。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao06' => [                [                    'name' => '员工提成', 'temp_content' => '#username#，您的客户#friend_name#已下单，本次获得#money#元。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'fenxiao08' => [                [                    'name' => '额外红包', 'temp_content' => '#username#，管理员送您红包#money#元，已发放到您的微信零钱中。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'comm_agent' => [                [                    'name' => '代理提成', 'temp_content' => '#username#，您的客户#friend_name#已下单，本次获得#money#元。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'self_buy' => [                [                    'name' => '客户支付成功', 'temp_content' => '#username#，您已支付成功，有任何疑问请致电#work_phone#。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'work_phone', 'desc' => '联系方式', 'demo' => '13123452345'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'friend_buy' => [                [                    'name' => '好友购买', 'temp_content' => '#username#，刚刚好友#friend_name#通过您的推荐下单。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'friend_newfans' => [                [                    'name' => '好友到访', 'temp_content' => '#username#，刚刚好友#friend_name#访问过您的分享。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'pintuan_new' => [                [                    'name' => '新成员通知', 'temp_content' => '#username#，刚刚#friend_name#加入您的团，您的团已有#num#人。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友名称', 'demo' => '王小四'],                        ['code' => 'num', 'desc' => '人数', 'demo' => '1'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => ''],                    ],                    'is_auto' => true,                ]            ],            'pintuan_success' => [                [                    'name' => '拼团成功', 'temp_content' => '#username#，刚刚#friend_name#加入您的团，恭喜您组团成功。#activity_desc#详情 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => ''],                    ],                    'is_auto' => true,                ]            ],            'presale' => [                [                    'name' => '补款通知', 'temp_content' => '#username#，您预购的商品，已经开始补款啦，#activity_desc#立即补款请点击y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '新品开售', 'temp_content' => '#username#，新品已上线，#activity_desc#立即抢购 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '大卡开售', 'temp_content' => '#username#，#activity_desc#您预约的活动开始啦，速速抢购 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '活动开抢提醒', 'temp_content' => '尊敬的客户#username#您好，#activity_desc#活动开始了，详情点击 y0x.cn/#url_code#拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],            ],        ];        //极验        $oem_arr = [            '易宣' => [//72944                'fenxiao01' => ['70028679'],//一级分销  订单提醒6                'fenxiao02' => ['70028692'],//二级分销  订单提醒7                'fenxiao03' => ['70028693'],//三级分销  订单提醒7                'fenxiao05' => ['70028694'],//阅读红包  订单提醒9                'fenxiao06' => ['70028695'],//员工提成                'fenxiao08' => ['70028696'],//额外红包                'comm_agent' => ['70028697'],//代理提成                'self_buy' => ['70028698'],//客服支付成功                'friend_buy' => ['70028699'],//好友购买                'friend_newfans' => ['70028700'],//好友到访                'pintuan_new' => ['70028701'],//新成员通知                'pintuan_success' => ['70028702'],//拼团成功                'presale' => ['70028705', '70028706', '70028707', '70028709'],            ],            '金策' => [//73314                'fenxiao01' => ['70028983'],//一级分销  订单提醒6                'fenxiao02' => ['70028984'],//二级分销  订单提醒7                'fenxiao03' => ['70028985'],//三级分销  订单提醒7                'fenxiao05' => ['70028986'],//阅读红包  订单提醒9                'fenxiao06' => ['70028987'],//员工提成                'fenxiao08' => ['70028988'],//额外红包                'comm_agent' => ['70028989'],//代理提成                'self_buy' => ['70028990'],//客服支付成功                'friend_buy' => ['70028991'],//好友购买                'friend_newfans' => ['70028992'],//好友到访                'pintuan_new' => ['70028993'],//新成员通知                'pintuan_success' => ['70028994'],//拼团成功                'presale' => ['70028995', '70028996', '70028997', '70028998'],// 补款 新品 大卡 活动开抢            ],            '飞驰' => [//73315                'fenxiao01' => ['70029008'],//一级分销  订单提醒6                'fenxiao02' => ['70029009'],//二级分销  订单提醒7                'fenxiao03' => ['70029010'],//三级分销  订单提醒7                'fenxiao05' => ['70029011'],//阅读红包  订单提醒9                'fenxiao06' => ['70029012'],//员工提成                'fenxiao08' => ['70029013'],//额外红包                'comm_agent' => ['70029014'],//代理提成                'self_buy' => ['70029015'],//客服支付成功                'friend_buy' => ['70029016'],//好友购买                'friend_newfans' => ['70029017'],//好友到访                'pintuan_new' => ['70029018'],//新成员通知                'pintuan_success' => ['70029019'],//拼团成功                'presale' => ['70029020', '70029021', '70029022', '70029023'],// 补款 新品 大卡 活动开抢            ],            '联登' => [//73316                'fenxiao01' => ['70029029'],//一级分销  订单提醒6                'fenxiao02' => ['70029030'],//二级分销  订单提醒7                'fenxiao03' => ['70029031'],//三级分销  订单提醒7                'fenxiao05' => ['70029032'],//阅读红包  订单提醒9                'fenxiao06' => ['70029033'],//员工提成                'fenxiao08' => ['70029034'],//额外红包                'comm_agent' => ['70029035'],//代理提成                'self_buy' => ['70029036'],//客服支付成功                'friend_buy' => ['70029037'],//好友购买                'friend_newfans' => ['70029038'],//好友到访                'pintuan_new' => ['70029039'],//新成员通知                'pintuan_success' => ['70029040'],//拼团成功                'presale' => ['70029041', '70029042', '70029043', '70029044'],// 补款 新品 大卡 活动开抢            ],            '领泽' => [//73317                'fenxiao01' => ['70029051'],//一级分销  订单提醒6                'fenxiao02' => ['70029052'],//二级分销  订单提醒7                'fenxiao03' => ['70029053'],//三级分销  订单提醒7                'fenxiao05' => ['70029054'],//阅读红包  订单提醒9                'fenxiao06' => ['70029055'],//员工提成                'fenxiao08' => ['70029056'],//额外红包                'comm_agent' => ['70029057'],//代理提成                'self_buy' => ['70029058'],//客服支付成功                'friend_buy' => ['70029059'],//好友购买                'friend_newfans' => ['70029060'],//好友到访                'pintuan_new' => ['70029061'],//新成员通知                'pintuan_success' => ['70029062'],//拼团成功                'presale' => ['70029063', '70029064', '70029065', '70029066'],// 补款 新品 大卡 活动开抢            ],            '慧车网' => [//93057l                'fenxiao01' => ['70077324'],//一级分销  订单提醒6                'fenxiao02' => ['70077325'],//二级分销  订单提醒7                'fenxiao03' => ['70077326'],//三级分销  订单提醒7                'fenxiao05' => ['70077327'],//阅读红包  订单提醒9                'fenxiao06' => ['70077328'],//员工提成                'fenxiao08' => ['70077329'],//额外红包                'comm_agent' => ['70077330'],//代理提成                'self_buy' => ['70077331'],//客服支付成功                'friend_buy' => ['70077332'],//好友购买                'friend_newfans' => ['70077333'],//好友到访                'pintuan_new' => ['70077334'],//新成员通知                'pintuan_success' => ['70077335'],//拼团成功                'presale' => ['70077336', '70077337', '70077338', '70077339'],// 补款 新品 大卡 活动开抢            ],        ];        if ($get_key_arr) {            return $key_arr;        }        $oem_str = self::getSignature($system);        if (!array_key_exists($oem_str, $oem_arr)) {            $oem_str = '易宣';        }        if ($key_index && !$oem_arr[$oem_str][$key][$key_index]) {            $key_index = 0;        }        $key_temp_id = $oem_arr[$oem_str][$key][$key_index];        if (!$key_temp_id && !$demo) {            return [];        }        $temp_item = $key_arr[$key][$key_index];        if (!$temp_item) {            return [];        }        foreach ($temp_item['arguments'] as $ke => $vol) {            if ($vol['code'] == 'activity_desc') {                $temp_item['arguments'][$ke]['demo'] = $config['sms_' . $key . '_tips']?'【'.$config['sms_' . $key . '_tips'].'】':$vol['demo'];            }        }        self::$server_code = 'll';        if ($demo) {            $item_content = $temp_item['temp_content'];            $item_arguments = $temp_item['arguments'];            foreach ($item_arguments as $k => $v) {                $tmp_code = '#' . $v['code'] . '#';                $demo_val = $v['demo'];                if ($v['code'] == 'url_code') {                    $demo_val = 'x48MDn';                }                if ($v['code'] == 'activity_desc') {                    $demo_val = '【提示语】';                }                $item_content = str_replace($tmp_code, $demo_val, $item_content);            }            return $item_content;        } else {            return ['temp_id' => $key_temp_id, 'item' => $temp_item];        }    }    /**     * Desc:极验授权     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 17:50     * @param $GT_ID     * @param $GT_KEY     * @return false|string     */    private static function auth($GT_ID, $GT_KEY)    {        # 以下是加密部分，可以直接使用，加密方法详见文档。        $nonce = md5(uniqid()); //1.用户自己生成 timestamp（Unix 时间戳），精确到秒，取整；        $timestamp = (string)time(); //2.生成随机数nonce(注：最好是32位的) ;        $params = array($nonce, $GT_ID, $timestamp);        sort($params);        $join_str = implode("", $params); //3.一）将timestamp、nonce、GT_ID 这三个字符串依据字符串首位字符的ASCII码进行升序排列，如果第一个字符相同则比较下一位，依次类推。将三个字符串join成一个字符串；        $signature = bin2hex(hash_hmac('sha256', $join_str, $GT_KEY, true));        $arr = array(            "gt_id" => $GT_ID,            "timestamp" => $timestamp,            "nonce" => $nonce,            "signature" => $signature        ); //二）然后用GT_KEY对这个字符串做hamc-sha256 签名，以16进制编码；        $string = '';        foreach ($arr as $key => $value) {            $string = $string . $key . '=' . $value . ',';        }        $auth = substr($string, 0, -1); //将上述的值按照 #{k}=#{v} 并以 ‘,’ join在一起，返回签名认证字符串：        return $auth;    }    /**     * Desc:短信参数请求前格式化     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/9 14:12     * @param $input_arguments     * @param $temp_item     * @param $theme     * @param $system     * @param $uid     * @param $username     * @return array     */    public static function formatArguments($input_arguments, $temp_item, $theme, $system, $fans, $config)    {        if (!$temp_item['arguments']) {            return [];        }        $tmp_input_arguments = [];        foreach ($temp_item['arguments'] as $k => $v) {            if ($v['code'] == 'url_code') {                $path = '';                if ($temp_item['path']) {                    $path = $temp_item['path'];                }                $query = MODULE_NAME . "-" . $theme['id'] . "-" . $fans['uid'] . "-" . $theme['softkey'];                $wx_link = self::getUrlLink($system, $path, $query);                if ($wx_link['errcode'] == 0) {                    $wx_link = $wx_link['url_link'];                }                //todo  短链生成失败带处理                $yx_link = Poster::GetMainUrl($system, $wx_link, MODULE_NAME . '用户' . $fans['uid'] . '短信跳转');                $format_link = substr($yx_link, -6);                $tmp_input_arguments['url_code'] = $format_link;            } else if ($v['code'] == 'username') {                $tmp_val2 = '';                if ($fans) {                    $username = $fans['username'] ? $fans['username'] : $fans['nickname'];                    $tmp_val2 = '：' . mb_substr($username, 0, 4, "UTF-8");                }                $tmp_val1 = mb_substr($config['sms_notice_signname'] ? $config['sms_notice_signname'] : $config['jubf'], 0, 7, "UTF-8");                $tmp_input_arguments['username'] = $tmp_val1 . $tmp_val2;            } else if ($v['code'] == 'friend_name') {                $tmp_input_arguments['friend_name'] = mb_substr($input_arguments[$v['code']], 0, 4, "UTF-8");            } else if ($v['code'] == 'activity_desc') {                if (empty($v['demo'])) {                    $tmp_input_arguments['activity_desc'] = '';                } else {                    if($v['demo']=='【提示语】'){                        $tmp_input_arguments['activity_desc'] = '';                    }else{                        $tmp_input_arguments['activity_desc'] = $v['demo'];                    }                }            }else if($v['code']=='desc'){                $tmp_input_arguments['desc'] = mb_substr($config['sms_self_buy_tips'],0,12,"UTF-8");            } else {                $tmp_input_arguments[$v['code']] = $input_arguments[$v['code']];            }        }        return $tmp_input_arguments;    }    /**     * Desc:获取小程序链接     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 18:19     * @param $system     * @param string $path 为空 默认首页     * @param string $query 参数 可为空     * @param string $env_version     * @return array|mixed     */    public static function getUrlLink($system, $path = '', $query = '', $env_version = 'release')    {        $url = self::$url_link;        $data = [            'is_expire' => true,            'expire_type' => 1,            'expire_time' => strtotime('+1week'),            'expire_interval' => 7,            'env_version' => $env_version        ];        if ($path) {            $data['path'] = $path;        }        if ($query) {            $data['query'] = $query;        }        $res = PostByAccessToken($system, $url, $data);        return $res ? json_decode($res, true) : [];    }    /**     * Desc:格式化短信发送内容     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 18:29     * @param $temp_content     * @param $arguments     * @param $user_arguments     * @return mixed|string|string[]     */    private static function formatContent($temp_content, $arguments, $user_arguments)    {        if ($temp_content && $arguments && $user_arguments) {            foreach ($arguments as $k => $v) {                $temp_code = '#' . $v['code'] . '#';                foreach ($user_arguments as $kk => $vv) {                    if ($kk == $v['code']) {                        $temp_content = str_replace($temp_code, $vv, $temp_content);                    }                }            }        }        return $temp_content;    }    /**     * Desc:获取短信内容计算短信条数     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 18:44     * @param $content     * @return false|float     */    public static function getSmsContentFlag($content)    {        return ceil($content / 63);    }    /**     * Desc:判断余额能否发短信     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 18:35     * @param $themeid     * @param $sms_num     * @return bool     */    public static function checkCanSendSms($themeid, $sms_num)    {        $totalpayfee = (float)Order::getRealByThemeIdnew($themeid);        if (DOMAIN1 == "www.yixuan.net") {            $totalpayfee = (float)self::getAmountRecordTotal($themeid);        }        if ($totalpayfee < 0.1) {            return false;        }        $sms_total_amount = 0.1 * $sms_num;        if ($totalpayfee < $sms_total_amount) {            return false;        }        return true;    }    /**     * Desc:插入待发送队列     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 17:29     * @param $data     */    private static function addSmsQueue($data)    {        return $insertid = db_insert(t_sms_wait_send_queue, $data);    }    /**     * Desc:判断时间范围内 用户是否进入活动链接 判断用户是否被激活     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/12 10:08     * @param $themeid     * @param $uid     * @param $config     * @return bool     */    private static function validateUserIsActivity($themeid, $uid, $config)    {        if ($config['sms_user_pause'] && (int)$config['sms_user_pause'] > 0) {            $item = db_get(t_userdata_all, ['themeid' => $themeid, 'uid' => $uid]);            if ($item) {                $start_time = $item['update_time'];                $end_time = date("Y-m-d H:i:s", time());                $sql = " select count(*) as cnt from " . tablename(t_sms_send_log) .                    " where themeid=$themeid and uid=$uid and created_at between '" . $start_time . "' and '" . $end_time . "'";                $send_sms_total = db_find($sql)['cnt'];                if ($send_sms_total > $config['sms_user_pause']) {                    return false;                }            }        }        return true;    }    /**     * Desc:创建短信发送日志     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 09:13     * @param $data     * @return mixed     */    public static function addSendLog($data)    {        return $insertid = db_insert(t_sms_send_log, $data);    }    /**     * Desc:批量插入sql语句     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/12 11:35     * @param $table     * @param $fileds     * @param $vals     * @return mixed     */    public static function batchInsert($table, $fileds, $vals)    {        $sql = " insert into " . $table . " ($fileds) " . " VALUES " . $vals;        return db_query($sql);    }    /**     * Desc:批量发送短信 模版消息  存在一定延时概率     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/5 16:15     * @param $mobileArr array     * @param $template_params_arr array     * @param $config     * @return false|mixed     */    public static function sendBatchSms($mobile, $signName, $temp_code, $template_params_arr)    {        try {            $res = ['status' => 400, 'msg' => 'fail', 'trade_id' => ''];            $params = self::formatParams($mobile, 2, $signName, $temp_code, $template_params_arr);            $response = self::request($params);            if ($response['Code'] == 'OK') {                //todo  执行记录入库                $res = ['status' => 200, 'msg' => 'success', 'trade_id' => $response['BizId']];            } else {                $res = ['status' => $response['Code'], 'msg' => 'fail', 'trade_id' => $response['BizId']];            }            return $res;        } catch (Exception $e) {            yxlog('短信批量发送异常:' . $e->getMessage());        }    }    /**     * Desc:格式化请求参数     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/10 17:18     * @param $mobileArr     * @param $type     * @param $signName     * @param $temp_code     * @param $template_params_arr     * @return array     */    public static function formatParams($mobileArr, $type, $signName, $temp_code, $template_params_arr)    {        // *** 需用户填写部分 ***        // fixme 必填：是否启用https//        $security = false;        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息//        $accessKeyId = self::$access_key_id;//        $accessKeySecret = self::$access_key_secret;        if ($type == 1) {            //单条            // fixme 必填: 短信接收号码            $params["PhoneNumbers"] = $mobileArr;            // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign            $params["SignName"] = $signName;            // fixme 必填: 短信模版Code，应严格按"模版CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template            $params["TemplateCode"] = $temp_code;            // fixme 可选: 设置模版参数, 假如模版中存在变量需要替换则为必填项            $params['TemplateParam'] = $template_params_arr;            $params['OutId'] = MODULE_NAME;//外部拓展流水号            // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***            if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {                $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);            }            $params['Action'] = 'SendSms';        } else {            //多条            // fixme 必填: 待发送手机号。支持JSON格式的批量调用，批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式            $params["PhoneNumberJson"] = $mobileArr;            // fixme 必填: 短信签名，支持不同的号码发送不同的短信签名，每个签名都应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign            $params["SignNameJson"] = $signName;            // fixme 必填: 短信模版Code，应严格按"模版CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template            $params["TemplateCode"] = $temp_code;            // fixme 必填: 模版中的变量替换JSON串,如模版内容为"亲爱的${name},您的验证码为${code}"时,此处的值为            // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败            $params["TemplateParamJson"] = $template_params_arr;            $params['OutId'] = MODULE_NAME;//外部拓展流水号            // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***            $params["TemplateParamJson"] = json_encode($params["TemplateParamJson"], JSON_UNESCAPED_UNICODE);            $params["SignNameJson"] = json_encode($params["SignNameJson"], JSON_UNESCAPED_UNICODE);            $params["PhoneNumberJson"] = json_encode($params["PhoneNumberJson"], JSON_UNESCAPED_UNICODE);            if (!empty($params["SmsUpExtendCodeJson"]) && is_array($params["SmsUpExtendCodeJson"])) {                $params["SmsUpExtendCodeJson"] = json_encode($params["SmsUpExtendCodeJson"], JSON_UNESCAPED_UNICODE);            }            $params['Action'] = 'SendBatchSms';        }        $params['RegionId'] = 'cn-hangzhou';        $params['Version'] = '2017-05-25';        return $params;    }    public static function request($params, $security = false, $method = 'POST')    {        $domain = 'dysmsapi.aliyuncs.com';        $apiParams = array_merge(array(            "SignatureMethod" => "HMAC-SHA1",            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),            "SignatureVersion" => "1.0",            "AccessKeyId" => self::$access_key_id,            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),            "Format" => "JSON",        ), $params);        ksort($apiParams);        $sortedQueryStringTmp = "";        foreach ($apiParams as $key => $value) {            $sortedQueryStringTmp .= "&" . self::encode($key) . "=" . self::encode($value);        }        $stringToSign = "${method}&%2F&" . self::encode(substr($sortedQueryStringTmp, 1));        $sign = base64_encode(hash_hmac("sha1", $stringToSign, self::$access_key_secret . "&", true));        $signature = self::encode($sign);        $url = ($security ? 'https' : 'http') . "://{$domain}/";        try {            $content = self::fetchContent($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");            $res = json_decode($content, true);            if ($res['Code'] != 'OK') {                $error = self::getErrorMessage($res['Code']);                yxlog('阿里短信接口数据获取失败:' . $error);            }            return $res;        } catch (\Exception $e) {            return false;        }    }    private static function encode($str)    {        $res = urlencode($str);        $res = preg_replace("/\+/", "%20", $res);        $res = preg_replace("/\*/", "%2A", $res);        $res = preg_replace("/%7E/", "~", $res);        return $res;    }    private static function fetchContent($url, $method, $body)    {        $ch = curl_init();        if ($method == 'POST') {            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);        } else {            $url .= '?' . $body;        }        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_TIMEOUT, 5);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        curl_setopt($ch, CURLOPT_HTTPHEADER, array(            "x-sdk-client" => "php/2.0.0"        ));        if (substr($url, 0, 5) == 'https') {            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        }        $rtn = curl_exec($ch);        if ($rtn === false) {            // 大多由设置等原因引起，一般无法保障后续逻辑正常执行，            // 所以这里触发的是E_USER_ERROR，会终止脚本执行，无法被try...catch捕获，需要用户排查环境、网络等故障            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);        }        curl_close($ch);        return $rtn;    }    /**     * Desc:格式化错误信息     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 17:48     * @param $status     * @return string     */    private static function getErrorMessage($status)    {        $message = [            '1100' => '缺少身份验证参数-缺少请求头签名认证参数',            '1101' => '无效的时间戳-加密参数时间超过十分钟有效期',            '1102' => 'ID不存在-无效的ID',            '1103' => '验证失败-签名认证加密参数验证失败',            '1104' => '短信平台金额不足,请联系易宣技术部gy-充值金额剩余不足',            '1105' => '身份验证参数错误-请求头签名认证参数错误',            '1200' => '参数错误-手机号、模版编号至少有一项为空、模版变量不合规定',            '1300' => '手机号参数错误-手机号码重复',            '1301' => '模版参数错误-无效的模版ID',            '1302' => '模版参数错误-模版审核未通过',            '1303' => '手机号参数错误-非指定运营商的手机号',            '1304' => '内部接口异常-极验内部接口异常',            '1305' => '模版变量异常-未配置的模版变量',            '1306' => '内部接口异常-验证码设置不成功',            '1307' => '手机号参数错误-单次传入手机个数超过5000条',            '2800' => '内部接口异常-极验内部接口异常',            '4000' => '未知错误-未知错误',            'isv.BUSINESS_LIMIT_CONTROL' => '短信发送频率超限',            'isv.DAY_LIMIT_CONTROL' => '已经达到您在控制台设置的短信日发送量限额值',            'isv.SMS_CONTENT_ILLEGAL' => '短信内容包含禁止发送内容,请修改短信文案',            'isv.SMS_SIGN_ILLEGAL' => '签名禁止使用,请在短信服务控制台中申请符合规定的签名',            'isp.RAM_PERMISSION_DENY' => 'RAM权限不足。,请为当前使用的AK对应子账号进行授权：AliyunDysmsFullAccess（管理权限）',            'isv.OUT_OF_SERVICE' => '短信平台余额不足，请联系易宣技术部al。余额不足时，套餐包中即使有短信额度也无法发送短信',            'isv.PRODUCT_UN_SUBSCRIPT' => '未开通云通信产品的阿里云客户',            'isv.PRODUCT_UNSUBSCRIBE' => '产品未开通',            'isv.ACCOUNT_NOT_EXISTS' => '账户不存在，使用了错误的账户名称或AK',            'isv.ACCOUNT_ABNORMAL' => '账户异常',            'isv.SMS_TEMPLATE_ILLEGAL' => '短信模版不存在，或未经审核通过',            'isv.SMS_SIGNATURE_ILLEGAL' => '签名不存在，或未经审核通过',            'isv.INVALID_PARAMETERS' => '参数格式不正确',            'isv.MOBILE_NUMBER_ILLEGAL' => '机号码格式错误',            'isv.MOBILE_COUNT_OVER_LIMIT' => '参数PhoneNumbers中指定的手机号码数量超出限制',            'isv.TEMPLATE_MISSING_PARAMETERS' => '模版缺少变量',            'isv.BLACK_KEY_CONTROL_LIMIT' => '黑名单管控',            'isv.PARAM_LENGTH_LIMIT' => '参数超出长度限制',            'isv.PARAM_NOT_SUPPORT_URL' => '不支持URL',            'isv.AMOUNT_NOT_ENOUGH' => '账户余额不足',            'SignatureDoesNotMatch' => '签名（Signature）加密错误',            '00' => 'success',            '01' => '参数有误',            '02' => '数字签名错误',            '03' => '企业ID有误',            '04' => '短信平台余额不足-请联系易宣技术部ll',            '05' => '号码格式有误',            '06' => '未知错误',            '07' => '号码数量超限',            '08' => '请求频率限制',            '09' => '服务器内部错误',            '10' => '签名过长',            '11' => 'taskid不存在',            '12' => 'tag参数大于32位',            '13' => '账户不存在或已停用',            '14' => '待审核',            '15' => '驳回',            '16' => '无匹配模板',            '17' => '未发送',            '18' => '模板内容不能超过600字',            '19' => '短信字数超限',            '20' => '签名不存在，请先添加签名',            '21' => '价格计算错误',            '22' => '模板有误或没有审核',            '23' => '时间戳差异过大，与系统时间差异超过5分钟',            '24' => '签名ID不存在',            '25' => '签名已存在',            '28' => '限制发送时间',            '31' => 'AppId错误',            '38' => '签名参数错误',            '39' => '签名格式错误',            '40' => '非法的IP地址',            '41' => '产品未开通',            '42' => '账号无配置',            '43' => '未配置效验通道',            '44' => '身份证号格式错误',            '45' => '银行卡号格式错误',        ];        if (isset ($message[$status])) {            return $message[$status];        }        return $status;    }    /**     * Desc:短信发送频率验证     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/9 16:36     * @param $themeid     * @param $phone     * @return bool     */    private static function validateSendRule($themeid, $phone)    {        //手机号        $phone = (int)$phone;        //手机号格式校验        if (!CheckPhoneNumber($phone)) {            return false;        }        $res = db_get(t_sms_send_flag, ['themeid' => $themeid, 'mobile' => $phone]);        if (!$res) {            return true;        }        // 一分钟一条        $time = time();        $prev_time = strtotime($res['created_at']);        $diff_minute = floor(($time - $prev_time) % 86400 / 60);        if ($diff_minute <= 1) {            //小于等于1分钟进入队列            $msg = '同一手机号一分钟只能发送一条短信;' . '短信投放失败手机号:' . $phone;            $res = ['status' => 0, 'msg' => $msg];            yxlog($res, '短信发送失败');            return false;        }        // 24小时 50条        $before_time = date("Y-m-d H:i:s", strtotime("-24 hour"));        $now_time = date("Y-m-d H:i:s", time());        $sql = " select count(*) as cnt from " . tablename(t_sms_send_log) . " where themeid=$themeid and mobile='$phone' and created_at between '" . $before_time . "' and '" . $now_time . "'";        $phone_flag_total = db_find($sql)['cnt'];        if ($phone_flag_total > 50) {            $msg = '同一手机号24小时只能发送50条短信;' . '短信投放失败手机号:' . $phone;            $res = ['status' => 0, 'msg' => $msg];            yxlog($res, '短信发送失败');            return false;        }        return true;    }    /**     * Desc:获取使用短信条数     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 13:41     * @param $themeid     * @return mixed     */    public static function getUsedSmsTotal($themeid, $type = '', $status = 1)    {        if (!db_tableexists(t_sms_send_log)) {            return 0;        }        if ($type == 'day') {            //获取今日发送成功短信条数            $sql2 = " select sum(sms_num) as cnt from " . tablename(t_sms_send_log) . " where themeid=$themeid and status=$status and TO_DAYS(created_at) = TO_DAYS(NOW())";        } elseif ($type == 'hour') {            //获取一小时内 发送成功短信条数            $sql2 = " select sum(sms_num) as cnt from " . tablename(t_sms_send_log) . " where themeid=$themeid and status=$status and created_at > DATE_SUB(NOW(), INTERVAL 60 MINUTE)";        } else {            $sql2 = " select sum(sms_num) as cnt from " . tablename(t_sms_send_log) . " where themeid=$themeid and status=$status ";        }        $used_total = db_find($sql2)['cnt'];        return max(0, $used_total);    }    public static function llSmsSend($mobile_arr, $template_code, $template_params_arr = [],$time, $type)    {        $post_url = 'https://apis.shlianlu.com/sms/trade/template/send';        $params["Type"] = 3;        $params["PhoneNumberSet"] = $mobile_arr;        $params["TemplateId"] = $template_code;        if (!$template_params_arr) {            $template_params_arr = [];        }        if (!empty($time)) {            $params["TaskTime"] = $time;        }        $params["TemplateParamSet"] = $template_params_arr;        if ($type) {            //营销短信            $format_json = self::llFormatParams($params, 'sales');        } else {            $format_json = self::llFormatParams($params);        }        $response = self::llPostCurl($format_json, $post_url);        //dump($response);        if ($response['message'] == 'success') {            $res = ['status' => 200, 'msg' => 'success', 'data' => $response];        } else {            $res = ['status' => $response['status'], 'msg' => $response['message']];            yxlog($response['message'], '短信发送失败');        }        return $res;    }    /**     * Desc:查询联麓短信状态     * User: mf     * Email:     * Time: 2023/8/4 15:54     * @param $TaskId     * @return true|void     */    public static function llReport($system,$tradeId = '')    {        if (!db_tableexists(t_sms_send_log)) {            return false;        }        $time = round(microtime(true) * 1000);        $flog = db_get(t_sms_send_log, ['status' => 6,'fixed_time <'=>$time]);        if (empty($flog)){            $flog = db_get(t_sms_send_log, ['status' => 2,'fixed_time <'=>$time]);        }        $TaskId = $tradeId?$tradeId:$flog['tradeId'];        if(empty($TaskId)){            return false;        }        $post_url = 'https://apis.shlianlu.com/sms/trade/report';        $params["TaskId"] = $TaskId;        $params["pageNo"] = 1;        $params["pageSize"] = 10000;        $format_json = self::llFormatParams($params, 'sales');        $response = self::llPostCurl($format_json, $post_url);        if ($response['message'] == 'success') {            $data = $response['data'];            //查询不到data信息，默认为发送失败。目前只有在短信方后台终止发送才会出现这种情况            if(!$data){                db_update(t_sms_send_log,array('status'=>2,'trade_status'=>'FAIL'),array('tradeId'=>$TaskId));                return false;            }            $respTime = strtotime($data[0]['respTime'])*1000;            db_update(t_sms_send_log,array('status'=>1,'trade_status'=>'DELIVRD','fixed_time'=>$respTime),array('tradeId'=>$TaskId));            self::smsPostOa($system,$TaskId);            return true;        }elseif($response['message'] == '驳回'||$response['status']==15){            db_update(t_sms_send_log,array('status'=>2,'trade_status'=>$response['message']),array('tradeId'=>$TaskId));            return true;        }        return false;    }    public static function smsPostOa($system,$TaskId=0)    {        if (!db_tableexists(t_sms_send_log)) {            return false;        }        if (!db_fieldexists(t_sms_send_log, 'is_oa')) {            $sql = "ALTER TABLE ".tablename(t_sms_send_log)." ADD COLUMN `is_oa` int(1) default 0 comment '是否上报oa';";            db_query($sql);        }        //检测正在审核的短信--修改状态        self::llReport($system);        $postdata = [];        if (empty($TaskId)){            //查询 群发短信还没上报oa的            $sql = "SELECT * FROM ".tablename(t_sms_send_log)." WHERE status=1 and is_oa=0 and (type='llfast' or type='senior')";            $get_sms = db_find($sql);            if (empty($get_sms)){                $sql = "SELECT * FROM ".tablename(t_sms_send_log)." WHERE status=1 and type!='llfast' and type!='senior' order by id desc";                $get_sms = db_find($sql);                if (empty($get_sms)){                    return;                }            }        }else{            $get_sms = db_get(t_sms_send_log,array('tradeId'=>$TaskId));        }        $theme = Theme::getThemeById($get_sms['themeid']);        if(empty($theme['xiaoshou'])){            yxlog('未找到销售','短信上报失败');            return ;        }        //判断是不是即时短信        if($get_sms['type']!='llfast' && $get_sms['type']!='senior'){            $count_sum_sql = "SELECT count(id) as mobile_count,sum(sms_num) as sms_anum,created_at,fixed_time,content,admin_name,ip,themeid,type  FROM ".tablename(t_sms_send_log)." WHERE themeid=".$get_sms['themeid']." and status=1 and type!='llfast' and type!='senior'";            $postdata['type']=1;        }else{//是群发短信            $count_sum_sql = "SELECT count(id) as mobile_count,sum(sms_num) as sms_anum,created_at,fixed_time,content,admin_name,ip,themeid,type  FROM ".tablename(t_sms_send_log)." WHERE tradeId=".$get_sms['tradeId']." and status=1 AND themeid=".$get_sms['themeid'];            $postdata['type']=2;        }        $count_sum = db_find($count_sum_sql);        if(!empty($get_sms['fixed_time'])){            $postdata['fixed_at'] = date("Y-m-d H:i:s",$get_sms['fixed_time']/1000);//发送时间        }else{            $postdata['fixed_at'] = $get_sms['created_at'];//发送时间        }        $postdata['tradeid'] = $get_sms['tradeId'];//任务ID        $postdata['software'] = MODULE_NAME.'-'.$get_sms['themeid'];//活动编号        $postdata['xiaoshou'] = $theme['xiaoshou'];//销售        $postdata['admin_name'] = $get_sms['admin_name'];//发送人        $postdata['ip'] = $get_sms['ip'];//发送ip        $postdata['created_at'] = $get_sms['created_at'];//创建时间        $postdata['companyname'] = '【'.mb_substr($_G['companyname'],0,2).'】';//签名        $postdata['content'] = $get_sms['content'];//短信内容        $postdata['mobile_count'] = $count_sum['mobile_count'];//手机号码数        $postdata['sms_num'] = $count_sum['sms_anum'];//计费数        $res = Poster::Getbanklist($system,'smsLog_receive',$postdata);        if(($res['error']!=1 || $res['msg']=='该记录已存在') && ($get_sms['type']=='llfast' || $get_sms['type']=='senior')){            db_update(t_sms_send_log,array('is_oa'=>1),array('tradeId'=>$get_sms['tradeId']));        }else if($res['error']==1){            $postdata['res']=$res;            yxlog($postdata,'短信上报失败');        }        return $res;    }    /**     * Desc:格式化请求参数     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 09:43     * @param $input     * @return false|string     */    public static function llFormatParams($input, $type = 'notify')    {        $ll_appid = $type == 'notify' ? self::$ll_notify_appid : self::$ll_sales_appid;        $ll_appkey = $type == 'notify' ? self::$ll_notify_appkey : self::$ll_sales_appkey;        $base_params = [            'MchId' => self::$ll_mchid,            'AppId' => $ll_appid,            'Version' => self::$ll_version,            'TimeStamp' => self::getMillisecond(),            'SignType' => self::$ll_signType,        ];        if ($input) {            $merge_params = array_merge($base_params, $input);        } else {            $merge_params = $base_params;        }        $merge_params['Signature'] = self::llMakeSign($merge_params, $ll_appkey);        return json_encode($merge_params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);    }    /**     * Desc:获取毫秒级时间戳     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 09:20     * @return mixed|string     */    public static function getMillisecond()    {        $time = explode(" ", microtime());        $time = $time[1] . ($time[0] * 1000);        $time2 = explode(".", $time);        return $time2[0];    }    /**     * Desc:生成签名     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 09:12     * @param $params     * @param $ll_appKey     * @return string     */    public static function llMakeSign($params, $ll_appKey)    {        ksort($params);        $string = self::llToUrlParams($params);        //签名步骤二：在string后加入KEY        $string = $string . "&key=" . $ll_appKey;        //签名步骤三：MD5加密或者HMAC-SHA256        $string = md5($string);        //签名步骤四：所有字符转为大写        return strtoupper($string);    }    /**     * Desc:格式化URL参数     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 09:12     * @param $params     * @return string     */    public static function llToUrlParams($params)    {        $buff = "";        $noSignKey = array("Signature", "ContextParamSet", "TemplateParamSet", "SessionContextSet", "PhoneNumberSet", "SessionContext", "PhoneList", "phoneSet");        foreach ($params as $k => $v) {            if (!in_array($k, $noSignKey) && $v != "" && !is_array($v)) {                $buff .= $k . "=" . $v . "&";            }        }        return trim($buff, "&");    }    public static function llPostCurl($json, $url, $second = 5)    {        $ch = curl_init();        //设置超时        curl_setopt($ch, CURLOPT_TIMEOUT, $second);        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);        //post提交方式        curl_setopt($ch, CURLOPT_POST, TRUE);        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //获取的信息以文件流的形式返回，而不是直接输出        curl_setopt($ch, CURLOPT_HEADER, false);        if (false !== strpos($url, "https")) {            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        }        $response = curl_exec($ch); // 已经获取到内容，没有输出到页面上。        curl_close($ch);        return json_decode($response, true);    }    static function request_data($url, $data = [], $method = 'GET', $auth = '')    {        if ($auth) {            $header = [                'Content-Type: application/json',                'Accept: application/json',                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63',                'Authorization: ' . $auth            ];        }        $redata = $data ? json_encode($data) : '';        //CURL        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_FAILONERROR, false);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        //有post参数-设置        if ($method == 'POST') {            curl_setopt($ch, CURLOPT_POST, true);            curl_setopt($ch, CURLOPT_POSTFIELDS, $redata);        }        if ($method == 'PUT') {            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');            curl_setopt($ch, CURLOPT_POSTFIELDS, $redata);        }        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);        $result = curl_exec($ch);        curl_close($ch);        return $result ? json_decode($result, true) : [];    }    /**     * Desc:单次发送短息 验证码使用以及模版消息     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/5 16:15     * @param $mobile     * @param $template_param     * @param $config     * @return false|mixed     */    public static function aliSendSms($mobile, $signName, $temp_code, $template_params_arr)    {        $params = self::formatParams($mobile, 1, $signName, $temp_code, $template_params_arr);        $response = self::request($params);        if ($response['Code'] == 'OK') {            //todo  执行记录入库            $res = ['status' => 200, 'msg' => 'success', 'trade_id' => $response['BizId']];        } else {            $res = ['status' => $response['Code'], 'msg' => 'fail', 'trade_id' => $response['BizId']];        }        return $res;    }    /**     * Desc:插入短信发送记录     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 17:29     * @param $phone     * @param $data     */    private static function addSmsSendFlag($data)    {        $result = $insertid = db_insert(t_sms_send_flag, $data);        if (!$result) {            return false;        } else {            return true;        }    }    /**     * Desc:执行队列 发送短信     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 17:48     * @param $themeid     */    public static function sendSmsQueue($themeid, $config, $system, $send_limit = false)    {        if (!db_tableexists(t_sms_send_log)) {            return false;        }        $hour_limit = self::getUsedSmsTotal($themeid, 'hour');        if ($hour_limit > $config['sms_hour_max']) {            yxlog('队列执行短信发送失败，达到发送每小时阀值', '短信发送受限');            return;        }        $day_limit = self::getUsedSmsTotal($themeid, 'day');        if ($day_limit > $config['sms_day_max']) {            yxlog('队列执行短信发送失败，达到发送每日阀值', '短信发送受限');            return;        }        if ($send_limit) {            $sql = " select * from " . tablename(t_sms_wait_send_queue) . " where themeid=$themeid and server_code='gt' and status=5  limit 0,50";        } else {            $sql = " select * from " . tablename(t_sms_wait_send_queue) . " where themeid=$themeid and server_code='gt'  limit 0,50";        }        $res = db_select($sql);        //极验短信        if ($res) {            foreach ($res as $k => $v) {                $item = $v;                unset($item['status']);                $temp_item = self::getSmsTemplateArr($system, $config, $v['type'], $v['templateKey'])['item'];                $arguments = json_decode($v['des'], true);                $sms_length = (int)mb_strlen(self::formatContent($temp_item['temp_content'], $temp_item['arguments'], $arguments), 'UTF8');                $send_sms_flag = self::getSmsContentFlag($sms_length);                $can_send_sms = self::checkCanSendSms($themeid, $send_sms_flag);                if (!$can_send_sms) {                    $res = ['status' => 0, 'msg' => '账户余额不足,无法抵扣短信费用'];                    yxlog($res, '短信发送失败');                    break;                    die();                }                $result = self::sendSms($system, $item['themeid'], $item['mobile'], $v['type'], $v['templateKey'], json_decode($item['des'], true));                db_delete(t_sms_wait_send_queue, ['themeid' => $themeid, 'id' => $v['id']]);            }        }        //联麓短信        $sql = " select * from " . tablename(t_sms_wait_send_queue) . " where themeid=$themeid and server_code='ll' limit 0,50";        $ll_list = db_select($sql);        if($ll_list){            foreach ($ll_list as $key => $value){                $sms_length = (int)mb_strlen($value['content'], 'UTF8');                $sms_length += 4;                $send_sms_flag = self::getSmsContentFlag($sms_length);                $can_send_sms = self::checkCanSendSms($themeid, $send_sms_flag);                if (!$can_send_sms) {                    $res = ['status' => 0, 'msg' => '账户余额不足,无法抵扣短信费用'];                    yxlog($res, '短信发送失败');                    break;                    die();                }                $mobile_arr[0] = $value['mobile'];                $template_code = $value['templateId'];                $arguments = json_decode($value['des']);                $template_params_arr = [];                foreach ($arguments as $ke => $va) {                    array_push($template_params_arr, $va);                }                $response = Sms::llSmsSend($mobile_arr, $template_code, $template_params_arr, '','sales');                if ($response['msg'] == 'success') {                    $data['uid'] = $value['uid'];                    $data['mobile'] = $value['mobile'];                    $data['type'] = $value['type'];                    $data['status'] = 1;                    $data['templateId'] = $value['templateId'];                    $data['sms_num'] = ceil($sms_length / 67);;                    $data['content'] = $value['content'];                    $data['themeid'] = $themeid;                    $data['tradeId'] = $response['data']['taskId'];                    db_delete(t_sms_wait_send_queue, ['themeid' => $themeid, 'id' => $value['id']]);                    $insertid = db_insert(t_sms_send_log, $data);                }            }        }    }    /**     * Desc:阿里发送短信 批量还是单个     * User:cbw     * Email:17854288794@163.com     * Time: 2023/3/21 13:14     * @param $system     * @param $themeid     * @param $mobile     * @param $template_code     * @param $template_id     * @param string $template_params_arr     */    public static function beforeAliSmsSend($system, $themeid, $mobile, $template_code, $template_id, $template_params_arr = '')    {        global $_G;        $sign_name = '易宣';        if ($_G['companyname'] == '飞驰软件') {            $sign_name = '飞驰';        } elseif ($_G['companyname'] == '金策软件') {            $sign_name = '金策';        } elseif ($_G['companyname'] == '联登科技') {            $sign_name = '联登';        }        if (is_array($mobile)) {            $has_err = false;            $mobile_arr = $mobile;            $sign_name_arr = [];            //批量发送            $template_item = db_get(t_sms_template, ['id' => $template_id]);            $admin_name = $template_item['admin_name'] ? $template_item['admin_name'] : '系统发送';            $ip = $template_item['ip'] ? $template_item['ip'] : '';            if ($_G['username']) {                $admin_name = (string)$_G['username'];                $ip = (string)$_G['clientip'];            }            foreach ($mobile_arr as $kk => $vv) {                $arguments = [];                $user_arguments = [];                if ($template_item['diy_template_params']) {                    $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                    foreach ($diy_temp_params_arr as $k => $v) {                        array_push($arguments, ['code' => $v]);                        $user_arguments[$v] = $template_params_arr[$kk][$k];                    }                }                $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);                $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');                $send_sms_flag = self::getSmsContentFlag($sms_length);                $can_send_sms = self::checkCanSendSms($themeid, $send_sms_flag);                if (!$can_send_sms) {                    $res = ['status' => 0, 'msg' => '账户余额不足,无法抵扣短信费用'];                    yxlog($res, '短信发送失败');                    $has_err = true;                    break;                }                array_push($sign_name_arr, $sign_name);            }            if ($has_err) {                return;                die();            }            $response = self::sendBatchSms($mobile_arr, $sign_name_arr, $template_code, $template_params_arr);            yxlog('阿里短信批量发送回执：' . json_encode($response), '短信模版');            if ($response['status'] != 200) {                //发送失败                $error_log_str = "";                $queue_str = "";                $error = self::getErrorMessage($response['status']);                $tmp_trade_id = isset($response['trade_id']) ? $response['trade_id'] : '';                $error_send_total = 0;                foreach ($mobile_arr as $kk => $vv) {                    $arguments = [];                    $user_arguments = [];                    if ($template_item['diy_template_params']) {                        $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                        foreach ($diy_temp_params_arr as $k => $v) {                            array_push($arguments, ['code' => $v]);                            $user_arguments[$v] = $template_params_arr[$kk][$v];                        }                    }                    $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);                    $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');                    $send_sms_flag = self::getSmsContentFlag($sms_length);                    $tmp_desc = $response['status'] . '-' . $error;                    $uid = 0;                    $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $vv]);                    if ($get_order_info) {                        $uid = $get_order_info['uid'];                    }                    $error_log_str .= " ('$uid','$vv','diy',2,'$template_id','$tmp_trade_id','ERROR','$sms_item_content',$send_sms_flag,'$tmp_desc','$themeid','$admin_name','$ip'),";                    $tmp_arguments = json_encode($user_arguments, JSON_UNESCAPED_UNICODE);                    //获取发送失败次数                    $sql = " select count(*) as cnt from " . tablename(t_sms_send_log) . " where mobile=$vv and status=2 and templateId=$template_id";                    $error_send_total = db_find($sql)['cnt'];                    $queue_str .= " ('$uid','$vv','diy',$error_send_total,1,'$template_id','alisms','$tmp_arguments','$themeid','$admin_name','$ip'),";                }                if ($error_log_str) {                    $error_log_str = rtrim($error_log_str, ',');                    $error_log_sql = " insert into " . tablename(t_sms_send_log) . " (uid,mobile,type,status,templateId,tradeId,trade_status,content,sms_num,des,themeid,admin_name,ip) values " . $error_log_str;                    yxlog('短信批量插入失败：' . $error_log_sql, '批量短信');                    db_find($error_log_sql);                }                if ($queue_str) {                    $queue_str = rtrim($queue_str, ',');                    $queue_log_sql = " insert into " . tablename(t_sms_wait_send_queue) . " (uid,mobile,type,try_num,status,templateId,server_code,des,themeid,admin_name,ip) values " . $queue_str;                    yxlog('短信批量插入队列：' . $queue_log_sql, '批量短信');                    db_find($queue_log_sql);                }            } else {                $success_log_str = "";                $flag_str = "";                $tmp_trade_id = isset($response['trade_id']) ? $response['trade_id'] : '';                foreach ($mobile_arr as $kk => $vv) {                    $arguments = [];                    $user_arguments = [];                    if ($template_item['diy_template_params']) {                        $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                        foreach ($diy_temp_params_arr as $k => $v) {                            array_push($arguments, ['code' => $v]);                            $user_arguments[$v] = $template_params_arr[$kk][$v];                        }                    }                    $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);                    $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');                    $send_sms_flag = self::getSmsContentFlag($sms_length);                    $tmp_arguments = json_encode($user_arguments, JSON_UNESCAPED_UNICODE);                    $uid = 0;                    $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $vv]);                    if ($get_order_info) {                        $uid = $get_order_info['uid'];                    }                    //成功日志                    $success_log_str .= " ('$uid','$vv','diy',1,'$template_id','$tmp_trade_id','UNKNOW','$sms_item_content',$send_sms_flag,'$themeid','$admin_name','$ip'),";                    //记录日志                    $flag_str .= " ('$uid','$vv','diy',1,'$template_id',$send_sms_flag,'$sms_item_content','$tmp_trade_id','$tmp_arguments','$themeid','$admin_name','$ip'),";                }            }            if ($success_log_str) {                $success_log_str = rtrim($success_log_str, ',');                $success_log_sql = " insert into " . tablename(t_sms_send_log) . " (uid,mobile,type,status,templateId,tradeId,trade_status,content,sms_num,themeid,admin_name,ip) values " . $success_log_str;                yxlog('短信批量插入成功' . $success_log_sql, '批量短信');                db_find($success_log_sql);            }            if ($flag_str) {                $flag_str = rtrim($flag_str, ',');                $flag_log_sql = " insert into " . tablename(t_sms_send_flag) . " (uid,mobile,type,status,templateId,sms_num,content,tradeId,des,themeid,admin_name,ip) values " . $flag_str;                yxlog('短信批量插入' . $flag_log_sql, '批量短信');                db_find($flag_log_sql);            }            return;        } else {            $template_item = db_get(t_sms_template, ['id' => $template_id]);            $arguments = [];            $user_arguments = [];            if ($template_item['diy_template_params']) {                $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                foreach ($diy_temp_params_arr as $k => $v) {                    array_push($arguments, ['code' => $v]);                    $user_arguments[$v] = $template_params_arr[$k];                }            }            $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);            $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');            $send_sms_flag = self::getSmsContentFlag($sms_length);            $can_send_sms = self::checkCanSendSms($themeid, $send_sms_flag);            if (!$can_send_sms) {                $res = ['status' => 0, 'msg' => '账户余额不足,无法抵扣短信费用'];                yxlog($res, '短信发送失败');                die();            }            $uid = 0;            $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $mobile]);            if ($get_order_info) {                $uid = $get_order_info['uid'];            }            //单个发送            $response = self::aliSendSms($mobile, $sign_name, $template_code, $template_params_arr);            yxlog('短信发送回执：' . json_encode($response), '短信模版');            $admin_name = $template_item['admin_name'] ? $template_item['admin_name'] : '系统发送';            $ip = $template_item['ip'] ? $template_item['ip'] : '';            if ($_G['username']) {                $admin_name = (string)$_G['username'];                $ip = (string)$_G['clientip'];            }            if ($response['status'] != 200) {                //发送失败                $error = self::getErrorMessage($response['status']);                $res = ['status' => 0, 'msg' => $response['status'] . '-' . $error];                //记录发送失败日志                $data = [                    'uid' => $uid,                    'mobile' => $mobile,                    'type' => 'diy',                    'status' => 2,                    'templateId' => $template_id,                    'templateKey' => '',                    'tradeId' => isset($response['trade_id']) ? $response['trade_id'] : '',                    'trade_status' => 'ERROR',                    'content' => $sms_item_content,                    'sms_num' => $send_sms_flag,                    'admin_name' => $admin_name,                    'ip' => $ip,                    'des' => $response['status'] . '-' . $error,                    'themeid' => $themeid                ];                self::addSendLog($data);                //插入队列                $data = [                    'uid' => $uid,                    'mobile' => $mobile,                    'type' => 'diy',                    'status' => 1,                    'templateId' => $template_id,                    'templateKey' => '',                    'content' => '',                    'server_code' => 'alisms',                    'des' => json_encode($user_arguments),                    'themeid' => $themeid,                    'admin_name' => $admin_name,                    'ip' => $ip,                ];                self::addSmsQueue($data);            } else {                //发送成功                $data = [                    'uid' => $uid,                    'mobile' => $mobile,                    'type' => 'diy',                    'status' => 1,                    'templateId' => $template_id,                    'templateKey' => '',                    'tradeId' => isset($response['trade_id']) ? $response['trade_id'] : '',                    'content' => $sms_item_content,                    'sms_num' => $send_sms_flag,                    'des' => json_encode($arguments),                    'themeid' => $themeid,                    'admin_name' => $admin_name,                    'ip' => $ip                ];                $data['trade_status'] = 'UNKNOW';                //记录发送成功日志                self::addSendLog($data);                unset($data['trade_status']);                self::addSmsSendFlag($data);                $res = ['status' => 1, 'msg' => '发送成功'];            }        }    }    /**     * Desc:查询短信送达状态     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 16:01     * @return array     */    public static function reportSms($themeid)    {        if (!db_tableexists(t_sms_send_log)) {            return false;        }        //阿里查询        $sql = " select * from " . tablename(t_sms_send_log) . " where themeid=$themeid and type='diy' and status=1 and trade_status='UNKNOW'  order by created_at desc limit 20";        $list = db_select($sql);        if ($list) {            foreach ($list as $k => $v) {                $items = self::querySendDetails($v['mobile'], $v['tradeId'], date("Ymd", strtotime($v['created_at'])));//                if ($items){//                    yxlog($items,'短信查询返回');//                }                if ($items && $items['status'] = 200 && $items['data']) {                    $item = $items['data']['SmsSendDetailDTO'][0];                    $trade_status = '';                    if ($item['SendStatus'] == 2) {                        $trade_status = 'ERROR';                    } elseif ($item['SendStatus'] == 3) {                        $trade_status = 'DELIVRD';                    }                    if ($trade_status) {                        $where = ['themeid' => $themeid, 'mobile' => $v['mobile'], 'tradeId' => $v['tradeId']];                        $log_item = db_get(t_sms_send_log);                        $data = [                            'trade_status' => $trade_status,                            'trade_info' => json_encode($item)                        ];                        if ($log_item) {                            $tmp_sms_length = (int)mb_strlen($v['content'], 'UTF8');                            $tmp_sms_num = self::getSmsContentFlag($tmp_sms_length);                            if ($log_item['sms_num'] != $tmp_sms_num) {                                $data['sms_num'] = $tmp_sms_num;                            }                        }                        db_update(t_sms_send_log, $data, $where);                    }                }            }        }        if (self::$server_code == 'gt') {            //极验            $auth = self::auth(self::$gt_id, self::$gt_key);            $header = [                'Content-Type: application/x-www-form-urlencode',                'Accept: application/json',                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63',                'Authorization: ' . $auth            ];            $response = self::post_data(self::$message_report, [], 'POST', $header);            if ($response['status'] != 200) {                $error = self::getErrorMessage($response['status']);                $res = ['status' => 0, 'msg' => $response['status'] . '-' . $error];                yxlog($error, 'gt短信接口请求失败:');            } else {//                if ($response['data']){//                    yxlog($response['data'],'短信查询返回');//                }                $res = ['status' => 1, 'msg' => '拉取成功', 'data' => $response['data']];                $data = $response['data'];                if ($data) {                    foreach ($data as $k => $val) {                        $temp_arr = explode(",", $val);                        $where = ['themeid' => $themeid, 'mobile' => $temp_arr[1], 'tradeId' => $temp_arr[0]];                        $data = [                            'trade_status' => $temp_arr[4],                            'trade_info' => $val                        ];                        db_update(t_sms_send_log, $data, $where);                    }                }            }            return $res;        }    }    /**     * Desc:短信发送详情     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/12 09:15     * @param $phone     * @param $biz_id     * @param $send_date     * @return array     */    public static function querySendDetails($phone, $biz_id, $send_date)    {        // *** 需用户填写部分 ***        $params["PhoneNumber"] = $phone;        $params["BizId"] = $biz_id;        $params["SendDate"] = $send_date;        $params["PageSize"] = 10;        $params["CurrentPage"] = 1;        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***        $params['RegionId'] = 'cn-hangzhou';        $params['Action'] = 'QuerySendDetails';        $params['Version'] = '2017-05-25';        $response = self::request($params);        yxlog($response, '阿里短信查询');        if ($response['Code'] == 'OK') {            $res = ['status' => 200, 'msg' => 'success', 'data' => $response['SmsSendDetailDTOs']];        } else {            $res = ['status' => $response['Code'], 'msg' => 'fail', 'data' => $response['SmsSendDetailDTOs']];        }        return $res;    }    /**     * Desc:请求头     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 18:32     * @param $url     * @param $arr_header     * @param $postdata     * @return bool|string     */    private static function post_data($url, $data = [], $method = 'GET', $header = [])    {        $redata = $data ? json_encode($data) : '';        //CURL        $ch = curl_init();        curl_setopt($ch, CURLOPT_URL, $url);        curl_setopt($ch, CURLOPT_FAILONERROR, false);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        //有post参数-设置        if ($method == 'POST') {            curl_setopt($ch, CURLOPT_POST, true);            curl_setopt($ch, CURLOPT_POSTFIELDS, $redata);        }        if ($method == 'PUT') {            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');            curl_setopt($ch, CURLOPT_POSTFIELDS, $redata);        }        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);        $result = curl_exec($ch);        curl_close($ch);        return $result ? json_decode($result, true) : [];    }    /**     * Desc:获取短信送达状态数据列表     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 17:15     * @param $themeid     * @return array[]     */    public static function getTradeStatusCount($themeid)    {        $format_arr = [            ['trade_status' => 'UNKNOW', 'name' => '到达未知', 'total' => 0],            ['trade_status' => 'DELIVRD', 'name' => '到达成功', 'total' => 0],            ['trade_status' => 'ERROR', 'name' => '发送失败', 'total' => 0],        ];        $first_item = ['trade_status' => '', 'name' => '全部', 'total' => 0];        foreach ($format_arr as $k => $v) {            $item_total = self::getSmsLog($themeid, '', 0, 0, '', '', 0, '', true, $v['trade_status']);            $format_arr[$k]['total'] = $item_total;            $total += $item_total;        }        $first_item['total'] = $total;        array_unshift($format_arr, $first_item);        return $format_arr;    }    /**     * Desc:获取发送日志数据     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 15:59     * @param $themeid     * @param string $search     * @param int $page_start     * @param int $page_size     * @param string $start_day     * @param string $end_day     * @param int $status     * @param string $temp_id     * @param false $count     * @return int     */    public static function getSmsLog($themeid, $search = '', $page_start = 0, $page_size = 10, $start_day = '', $end_day = '', $status = 0, $type = '', $count = false, $trade_status = '',$tradeId = '')    {        $condition = "";        if ($search) {            $condition .= " AND b.nickname LIKE '" . $search . "'" . " or a.mobile LIKE '" . $search . "' " . " or b.username LIKE '" . $search . "'". " or a.content LIKE '" . $search . "'";        }        if ($start_day && $end_day && $start_day != $end_day) {            $condition .= "  and a.created_at between '" . $start_day . "' and '" . $end_day . "'";        }        if ($status) {            $condition .= " and a.status='$status'";        }        if ($tradeId) {            if($tradeId=='000000000000000000000'){                $condition .= " and type!='llfast' and type!='senior' ";            }else{                $condition .= " and a.tradeId='$tradeId'";            }        }        if ($trade_status) {            $condition .= " and a.trade_status='$trade_status'";        }        if ($type) {            if (strpos($type, 'diy') !== false) {                $tmp_template_id = substr($type, strpos($type, '_') + 1);                $condition .= " and a.templateId='$tmp_template_id'";            } else {                $condition .= " and a.type='$type'";            }        }        $condition .= " order by a.created_at desc, a.id desc";        if ($page_size && !$count) {            $condition .= " LIMIT " . $page_start . "," . $page_size;        }        $sql = "  from " . tablename(t_sms_send_log) . " as a " .            " left join " . tablename(t_fans) . " as b on a.uid=b.uid and a.themeid=b.themeid" .            " where a.themeid=$themeid " . $condition;        if ($count) {            return intval(db_fetchcolumn('SELECT count(a.sms_num)' . $sql));        } else {            $sql = " select a.*,b.nickname,avatar,username " . $sql;            return db_select($sql);        }    }    //以下为阿里相关方法    /**     * Desc:获取发送数组数据     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/9 19:18     * @param $themeid     * @return array[]     */    public static function getStatusCount($themeid,$tradeId='')    {        $format_arr = [            ['status' => -1, 'name' => '模版审核中', 'total' => 0],            ['status' => -2, 'name' => '待发送', 'total' => 0],            ['status' => 1, 'name' => '发送成功', 'total' => 0],            ['status' => 2, 'name' => '发送失败', 'total' => 0],            ['status' => 3, 'name' => '发送中断', 'total' => 0],            ['status' => 4, 'name' => '未知状态', 'total' => 0],            ['status' => 5, 'name' => '达到上限', 'total' => 0],            ['status' => 6, 'name' => '发送中', 'total' => 0],        ];        $first_item = ['status' => 0, 'name' => '全部', 'total' => 0];        $fail_total = 0;        foreach ($format_arr as $k => $v) {            if ($v['status'] < 1) {                if ($v['status'] == -1) {                    $item_total = self::getTemplateSmsData(0, 0, true);                    $format_arr[$k]['total'] = $item_total;                    $total += $item_total;                }                if ($v['status'] == -2) {                    $item_total = self::getSmsQueueList($themeid, 0, 0, true);                    $format_arr[$k]['total'] = $item_total;                    $total += $item_total;                }            } else {                $item_total = self::getSmsLog($themeid, '', 0, 0, '', '', $v['status'], '', true,'',$tradeId);                $format_arr[$k]['total'] = $item_total;                $total += $item_total;                if ($v['status'] > 1 && $v['status'] != 6) {                    $fail_total += $item_total;                }                if ($v['status'] == 6) {                    $fail_total += $item_total;                }            }        }        $first_item['total'] = $total;        array_unshift($format_arr, $first_item);        foreach ($format_arr as $k1 => $v1) {            if ($v1['total'] <= 0) {                unset($format_arr[$k1]);            }//            if ($v1['status'] == 2) {//                $format_arr[$k1]['total'] = $fail_total;//            }//            if ($v1['status'] == 6) {//                $format_arr[$k1]['total'] = $fail_total;//            }//            if ($v1['status'] > 2 && $v1['status'] != 6) {//                unset($format_arr[$k1]);//            }        }        return $format_arr;    }    /**     * Desc:获取模版待审核短信记录     * User:cbw     * Email:17854288794@163.com     * Time: 2023/5/5 15:52     */    public static function getTemplateSmsData($page_start = 0, $page_size = 10, $count = false)    {        $template_list = db_getall(t_sms_template, ['module_name' => MODULE_NAME, 'template_status' => 0]);        $template_ids = '';        foreach ($template_list as $key => $val) {            $template_ids .= $val['id'] . ',';        }        $template_ids = rtrim($template_ids, ',');        if ($template_ids) {            $condition = '';            $condition .= " order by a.id desc";            if ($page_size && !$count) {                $condition .= " LIMIT " . $page_start . "," . $page_size;            }            $sql = "  from " . tablename(t_sms_quick_mobile) . " as a " .                " left join " . tablename(t_sms_template) . " as b on a.template_id=b.id and a.themeid=b.themeid" .                " where a.template_id in ( " . $template_ids . " )";            if ($count) {                return intval(db_fetchcolumn('SELECT COUNT(*)' . $sql));            } else {                $sql = " select a.*,b.module_name,b.template_type,b.template_name,b.out_template_name,b.template_content,b.out_template_content,b.diy_template_params,b.show_template_params " . $sql;                $list = db_select($sql);                foreach ($list as $k => $v) {                    $list[$k]['type'] = 'diy';                    $list[$k]['content'] = $v['out_template_content'];                    $list[$k]['status'] = 4;                }                return $list;            }        } else {            if ($count) {                return 0;            } else {                return [];            }        }    }    public static function getSmsQueueList($themeid, $page_start = 0, $page_size = 10, $count = false)    {        $condition = "";        $condition .= " order by a.created_at desc,a.id desc";        if ($page_size && !$count) {            $condition .= " LIMIT " . $page_start . "," . $page_size;        }        $sql = "  from " . tablename(t_sms_wait_send_queue) . " as a " .            " left join " . tablename(t_fans) . " as b on a.uid=b.uid and a.themeid=b.themeid" .            " left join " . tablename(t_sms_template) . " as c on a.templateId=c.id and a.themeid=c.themeid" .            " where a.themeid=$themeid " . $condition;        if ($count) {            return intval(db_fetchcolumn('SELECT COUNT(*)' . $sql));        } else {            $sql = " select a.*,b.nickname,b.avatar,b.username,c.module_name,c.template_type,c.template_name,c.out_template_name,c.template_content,c.out_template_content,c.diy_template_params,c.show_template_params " . $sql;            $list = db_select($sql);            foreach ($list as $k => $v) {                $list[$k]['type'] = 'diy';                $list[$k]['content'] = $v['out_template_content'];                $list[$k]['status'] = 5;            }            return $list;        }    }    /**     * Desc:普通短信发送接口     * User: mf     * Email:732220552@qq.com     * Time: 2023/7/19 14:04     * @param $phone     * @param $name     * @param $context     * @param $time     * @param $tag     * @return mixed     */    public static function llNormalSend($phone = [], $name = '【易宣】', $context = '', $time = '',$Tag = '',$type='sales')    {        $post_url = 'https://apis.shlianlu.com/sms/trade/normal/send';        $params = ['Type' => '1', 'PhoneNumberSet' => $phone, 'SignName' => $name, 'SessionContext' => $context,'Tag'=>$Tag];        if (!empty($time)) {            $params['TaskTime'] = $time;        }        if ($type=='sales') {            //营销短信            $format_json = self::llFormatParams($params, 'sales');        }elseif($type=='notify'){            $format_json = self::llFormatParams($params);        }        $res = self::llPostCurl($format_json, $post_url);        if ($res['message'] == 'success') {            $res = ['status' => 200, 'msg' => 'success', 'data' => $res];        } else {            $res = ['status' => $res['status'], 'msg' => $res['message']];            yxlog($res['message'], '短信发送失败');        }        return $res;    }    /**     * Desc:联麓批量注册短信模板     * User: mf     * Email:732220552@qq.com     * Time: 2023/7/21 10:16     * @param $sign_id     */    public static function llBatch($sign_id, $config)    {        $key_arr = [            'fenxiao01' =>                [                    [                        'name' => '一级分销1', 'temp_content' => '{%username%}，刚刚{%friend_name%}通过您的推荐下单，本次获得{%money%}元。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao02' =>                [                    [                        'name' => '二级分销1', 'temp_content' => '{%username%}，您的好友{%friend_name%}推荐1人下单，您获得{%money%}元。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao03' =>                [                    [                        'name' => '三级分销1', 'temp_content' => '{%username%}，您的好友{%friend_name%}推荐1人下单，您获得{%money%}元。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao05' =>                [                    [                        'name' => '阅读红包', 'temp_content' => '{%username%}，新好友访问您的专属链接，您获得{%money%}元。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                        'arguments' => [                            ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                            ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                            ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                            ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                        ],                        'is_auto' => true,                    ]                ],            'fenxiao06' => [                [                    'name' => '员工提成', 'temp_content' => '{%username%}，您的客户{%friend_name%}已下单，本次获得{%money%}元。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'fenxiao08' => [                [                    'name' => '额外红包', 'temp_content' => '{%username%}，管理员送您红包{%money%}元，已发放到您的微信零钱中。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'comm_agent' => [                [                    'name' => '代理提成', 'temp_content' => '{%username%}，您的客户{%friend_name%}已下单，本次获得{%money%}元。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'money', 'desc' => '奖励金额', 'demo' => '10.00'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'self_buy' => [                [                    'name' => '客户支付成功', 'temp_content' => '{%username%}，您已支付成功，{%desc%}，有任何疑问请致电{%work_phone%}。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'desc', 'desc' => '描述', 'demo' => $config['sms_self_buy_tips']],                        ['code' => 'work_phone', 'desc' => '联系方式', 'demo' => '13123452345'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'friend_buy' => [                [                    'name' => '好友购买', 'temp_content' => '{%username%}，刚刚好友{%friend_name%}通过您的推荐下单。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'friend_newfans' => [                [                    'name' => '好友到访', 'temp_content' => '{%username%}，刚刚好友{%friend_name%}访问过您的分享。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ]            ],            'pintuan_new' => [                [                    'name' => '新成员通知', 'temp_content' => '{%username%}，刚刚{%friend_name%}加入您的团，您的团已有{%num%}人。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友名称', 'demo' => '王小四'],                        ['code' => 'num', 'desc' => '人数', 'demo' => '1'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => ''],                    ],                    'is_auto' => true,                ]            ],            'pintuan_success' => [                [                    'name' => '拼团成功', 'temp_content' => '{%username%}，刚刚{%friend_name%}加入您的团，恭喜您组团成功。{%activity_desc%}详情 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'friend_name', 'desc' => '好友姓名', 'demo' => '李小四'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => ''],                    ],                    'is_auto' => true,                ]            ],            'presale' => [                [                    'name' => '补款通知', 'temp_content' => '{%username%}，您预购的商品，已经开始补款啦，{%activity_desc%}立即补款请点击y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '新品开售', 'temp_content' => '{%username%}，新品已上线，{%activity_desc%}立即抢购 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '大卡开售', 'temp_content' => '{%username%}，{%activity_desc%}您预约的活动开始啦，速速抢购 y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],            ],            'currency' => [                [                    'name' => '活动开抢提醒', 'temp_content' => '尊敬的客户{%username%}您好，{%activity_desc%}活动开始了，详情点击xxxxx了解更多详情y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '到店通知', 'temp_content' => '恭喜您成功抢定{%youhui%}钜惠名额，{%activity_desc%}请于{%starttime%}到{%endtime%}到店激活,详情y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'youhui', 'desc' => '', 'demo' => ''],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'starttime', 'desc' => '开始时间', 'demo' => '某年某月某日'],                        ['code' => 'endtime', 'desc' => '结束时间', 'demo' => '某年某月某日'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],                [                    'name' => '未到店激活提醒', 'temp_content' => '尊敬的客户{%username%}您好，{%activity_desc%}本次超值钜惠活动距离结束仅剩{%datetime%},若您还未到店激活，请尽快到店激活，详情y0x.cn/{%url_code%}拒收请回复R',                    'arguments' => [                        ['code' => 'username', 'desc' => '当前用户姓名', 'demo' => '张小三'],                        ['code' => 'activity_desc', 'desc' => '活动描述', 'demo' => ''],                        ['code' => 'datetime', 'desc' => '剩余时间', 'demo' => '一天5小时'],                        ['code' => 'url_code', 'desc' => '活动参数', 'demo' => 'xxxxxx'],                    ],                    'is_auto' => true,                ],            ],        ];        $yes = 0;        $no = 0;        $array = [];        foreach ($key_arr as $key => $value) {            $count = count($value);            if ($count > 0) {                for ($i = 0; $i < $count; $i++) {                    $res = Sms::llTemplateCreate($sign_id, $value[$i]['name'], $value[$i]['temp_content']);                    $array[$key][$i] = $res['TemplateId'];                    if ($res['message'] == 'success') {                        $yes += 1;                    } else {                        $no += 1;                    }                }            }        }        echo 'yes:' . $yes . '--no' . $no;        die;    }    /**     * Desc:创建短信模板     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 17:45     * @param $sign_id     * @param $template_name     * @param $content     * @return mixed     */    public static function llTemplateCreate($sign_id, $template_name, $content)    {        $post_url = 'https://apis.shlianlu.com/sms/product/template/create';        $params = ['SignId' => $sign_id, 'content' => $content, 'TemplateName' => $template_name];        $format_json = self::llFormatParams($params);        $res = self::llPostCurl($format_json, $post_url);        return $res;    }    /**     * Desc:获取实例短信信息 包含短信内容 长度 条数     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/7 15:00     * @param $pinpai     * @param $system     * @param $config     * @param $themeid     * @param $key     * @param $key_index     * @return array     */    public static function getDemoSmsInfo($system, $config, $themeid, $key, $key_index = 0)    {        $pinpai = self::getSignature($system,$themeid);        $sms_top = '【' . $pinpai . '】';        $theme = Theme::getThemeById($themeid);        $sms_config = db_get(t_sms_config, ['themeid' => $themeid, 'module_name' => MODULE_NAME]);        $sms_notice_signname = $sms_config['sms_notice_signname'] ? $sms_config['sms_notice_signname'] : $theme['jubf'];        if ($key == 'self_buy') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'self_buy', 0, true);        } elseif ($key == 'friend_help') {            $temp_txt = self::getSmsTemplateArr($system,$config,'friend_help',0,true);        } elseif ($key == 'friend_help_success') {            $temp_txt = self::getSmsTemplateArr($system,$config,'friend_help_success',0,true);        } elseif ($key == 'friend_buy') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'friend_buy', 0, true);        } elseif ($key == 'friend_newfans') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'friend_newfans', 0, true);        } elseif ($key == 'mystery_boxes_new') {            if ($key_index == 0) {                $temp_txt = self::getSmsTemplateArr($system,$config,'mystery_boxes_new',0,true);            }            if ($key_index == 1) {                $temp_txt = self::getSmsTemplateArr($system,$config,'mystery_boxes_new',1,true);            }        } elseif ($key == 'pintuan_new') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'pintuan_new', 0, true);        } elseif ($key == 'pintuan_success') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'pintuan_success', 0, true);        } elseif ($key == 'presale') {            if ($key_index == 0) {                $temp_txt = self::getSmsTemplateArr($system, $config, 'presale', 0, true);            }            if ($key_index == 1) {                $temp_txt = self::getSmsTemplateArr($system, $config, 'presale', 1, true);            }            if ($key_index == 2) {                $temp_txt = self::getSmsTemplateArr($system, $config, 'presale', 2, true);            }            if ($key_index == 3) {                $temp_txt = self::getSmsTemplateArr($system, $config, 'presale', 3, true);            }        } elseif ($key == 'bargain_help') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'bargain_help', $key_index, true);        } elseif ($key == 'bargain_success') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'bargain_success', 0, true);        } elseif ($key == 'bargain_fail') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'bargain_fail', 0, true);        } elseif ($key == 'lottery_new') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'lottery_new', 0, true);        } elseif ($key == 'fenxiao06') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'fenxiao06', 0, true);        } elseif ($key == 'fenxiao01') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'fenxiao01', 0, true);        } elseif ($key == 'fenxiao02') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'fenxiao02', 0, true);        } elseif ($key == 'fenxiao03') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'fenxiao03', 0, true);        } elseif ($key == 'fenxiao05') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'fenxiao05', 0, true);        } elseif ($key == 'fenxiao08') {            $temp_txt = self::getSmsTemplateArr($system, $config, 'fenxiao08', 0, true);        }        if($sms_config['sms_'.$key.'_tips']){            $temp_txt = str_replace('【提示语】','【'.$sms_config['sms_'.$key.'_tips'].'】',$temp_txt);        }else{            $temp_txt = str_replace('【提示语】','',$temp_txt);        }        $sms_demo = $sms_top . $sms_notice_signname . $temp_txt;        $sms_length = (int)mb_strlen($sms_demo, 'UTF8');        $send_sms_flag = ceil($sms_length / 67);        $tips = '预计：' . $sms_length . '个字，' . $send_sms_flag . '条;';        return ['sms_demo' => $sms_demo, 'sms_length' => $sms_length, 'send_sms_flag' => $send_sms_flag, 'tips' => $tips];    }    /**     * Desc:判断当前场景值下的记录数     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/9 09:49     * @param $themeid     * @param $key     * @return mixed     */    public static function getSmsLogTotalByType($themeid, $key)    {        $sql = " select count(*) as cnt from " . tablename(t_sms_send_log) . " where themeid='$themeid' and type like '" . $key . " %'";        return db_find($sql)['cnt'];    }    /**     * Desc:格式化类型下模版信息     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/8 17:15     * @param $themeid     * @return array     */    public static function getSmsTemplateCountByType($themeid, $system)    {        $format_arr = [];        $first_item = ['temp_id' => '', 'name' => '全部', 'total' => 0];        $total = 0;        $config = Theme::getConfig($themeid);        if (db_tableexists(t_sms_config)) {            $has_sms_config = db_get(t_sms_config, ['themeid' => $themeid, 'module_name' => MODULE_NAME]);            $config = array_merge($config, $has_sms_config);        }        $res = self::getSmsTemplateArr($system, $config, 'all');        $sql = " select type as types from " . tablename(t_sms_send_log) . " where themeid=$themeid group by type";        $has_types = db_select($sql);        $has_types = self::formatSmsTypeArr($config);        $name_arr = getKeynameArray();        foreach ($res as $k => $v) {            if ($has_types) {                foreach ($has_types as $kk => $vv) {                    if ($vv['types'] == $k) {                        $item_total = self::getSmsLog($themeid, '', 0, 0, '', '', 0, $k, true);                        $temp = [                            'type' => $k,                            'name' => str_replace('短信:', '', $name_arr['sms_' . $k]),                            'total' => $item_total                        ];                        array_push($format_arr, $temp);                        $total += $item_total;                    }                }            }        }        //获取所有模版        $template_list = db_getall(t_sms_template, ['themeid' => $themeid, 'module_name' => MODULE_NAME]);        if ($template_list) {            foreach ($template_list as $tk => $tv) {                $item_total = self::getSmsLogTotalByTemplateId($themeid, $tv['id']);                $temp = [                    'type' => 'diy_' . $tv['id'],                    'name' => $tv['remark'],                    'total' => $item_total                ];                array_push($format_arr, $temp);                $total += $item_total;            }        }        $first_item['total'] = $total;        array_unshift($format_arr, $first_item);        return $format_arr;    }    /**     * Desc:格式化短信场景     * User:cbw     * Email:17854288794@163.com     * Time: 2023/5/12 11:19     * @param $config     * @return array     */    public static function formatSmsTypeArr($config)    {        $arr = [];        if ($config['sms_worker']) {            array_push($arr, ['types' => 'worker']);        }        if ($config['sms_self_buy']) {            array_push($arr, ['types' => 'self_buy']);        }        if ($config['sms_friend_help']) {            array_push($arr, ['types' => 'friend_help']);        }        if ($config['sms_friend_help_success']) {            array_push($arr, ['types' => 'friend_help_success']);        }        if ($config['sms_friend_buy']) {            array_push($arr, ['types' => 'friend_buy']);        }        if ($config['sms_friend_newfans']) {            array_push($arr, ['types' => 'friend_newfans']);        }        if ($config['sms_mystery_boxes_new']) {            array_push($arr, ['types' => 'mystery_boxes_new']);        }        if ($config['sms_pintuan_new']) {            array_push($arr, ['types' => 'pintuan_new']);        }        if ($config['sms_pintuan_success']) {            array_push($arr, ['types' => 'pintuan_success']);        }        if ($config['sms_presale'] > 0) {            array_push($arr, ['types' => 'presale']);        }        if ($config['sms_currency'] > 0) {            array_push($arr, ['types' => 'currency']);        }        if ($config['sms_bargain_help']) {            array_push($arr, ['types' => 'bargain_help']);        }        if ($config['sms_bargain_success']) {            array_push($arr, ['types' => 'bargain_success']);        }        if ($config['sms_bargain_fail']) {            array_push($arr, ['types' => 'bargain_fail']);        }        if ($config['sms_lottery_new']) {            array_push($arr, ['types' => 'lottery_new']);        }        if ($config['sms_fenxiao06']) {            array_push($arr, ['types' => 'fenxiao06']);        }        if ($config['sms_comm_agent']) {            array_push($arr, ['types' => 'comm_agent']);        }        if ($config['sms_fenxiao01']) {            array_push($arr, ['types' => 'fenxiao01']);        }        if ($config['sms_fenxiao02']) {            array_push($arr, ['types' => 'fenxiao02']);        }        if ($config['sms_fenxiao03']) {            array_push($arr, ['types' => 'fenxiao03']);        }        if ($config['sms_fenxiao05']) {            array_push($arr, ['types' => 'fenxiao05']);        }        if ($config['sms_fenxiao08']) {            array_push($arr, ['types' => 'fenxiao08']);        }        return $arr;    }    public static function getSmsLogTotalByTemplateId($themeid, $template_id)    {        $sql = " select count(*) from " . tablename(t_sms_send_log) . " where themeid=$themeid and templateId='$template_id' ";        return intval(db_fetchcolumn($sql));    }    /************联麓信息*************/    public static function formatUpdateSmsConfig($themeid, $config, $system, $params = [],$action)    {        global $_G;        $data = [];        $has_sms_config = db_get(t_sms_config, ['themeid' => $themeid, 'module_name' => MODULE_NAME]);        if (!$params) {            if (!$has_sms_config) {                $data['themeid'] = $themeid;                $data['module_name'] = MODULE_NAME;                $res = $insertid = db_insert(t_sms_config, $data);                return $res;            }        } else {                $data = [                    'open_yx_sms' => $params['open_yx_sms'],                    'sms_user_pause' => isset($params['sms_user_pause']) && $params['sms_user_pause'] ? $params['sms_user_pause'] : 5,                    'sms_day_max' => $params['sms_day_max'] ? $params['sms_day_max'] : 5000,                    'sms_hour_max' => $params['sms_hour_max'] ? $params['sms_hour_max'] : 1000,                    'sms_notice_signname' => $params['sms_notice_signname'] ? $params['sms_notice_signname'] : '',                    'sms_worker' => $params['sms_worker'],                    'sms_self_buy' => $params['sms_self_buy'],                    'sms_friend_buy' => $params['sms_friend_buy'],                    'sms_presale' => $params['sms_presale'],                    'sms_self_buy_tips' => $params['sms_self_buy_tips'],                    'sms_friend_newfans' => $params['sms_friend_newfans'],                    'sms_fenxiao01_tips' => $params['sms_fenxiao01_tips'],                    'sms_fenxiao02_tips' => $params['sms_fenxiao02_tips'],                    'sms_fenxiao03_tips' => $params['sms_fenxiao03_tips'],                    'sms_fenxiao05_tips' => $params['sms_fenxiao05_tips'],                    'sms_fenxiao06_tips' => $params['sms_fenxiao06_tips'],                    'sms_fenxiao08_tips' => $params['sms_fenxiao08_tips'],                    'sms_friend_buy_tips' => $params['sms_friend_buy_tips'],                    'sms_friend_newfans_tips' => $params['sms_friend_newfans_tips'],                    'sms_pintuan_new_tips' => $params['sms_pintuan_new_tips'],                    'sms_pintuan_success_tips' => $params['sms_pintuan_success_tips'],                    'sms_presale_tips' => $params['sms_presale_tips'],                ];            if ($config['isicon'] == 3 || $system['is_mystery_boxes'] > 0 || $system['is_mystery_boxes_feichi'] > 0) {                $data['sms_friend_help'] = $params['sms_friend_help'];                $data['sms_friend_help_success'] = $params['sms_friend_help_success'];            }            if ($system['is_mystery_boxes'] > 0 || $system['is_mystery_boxes_feichi'] > 0) {                $data['sms_mystery_boxes_new'] = $params['sms_mystery_boxes_new'];            }            if ($config['maxcountall'] > 1) {                $data['sms_pintuan_new'] = $params['sms_pintuan_new'];                $data['sms_pintuan_success'] = $params['sms_pintuan_success'];            }            if ($system['ispresale'] == 1) {                $data['sms_presale'] = $params['sms_presale'];            }            if ($system['ruanjian'] == 5) {                $data['sms_bargain_help'] = $params['sms_bargain_help'];                $data['sms_bargain_success'] = $params['sms_bargain_success'];                $data['sms_bargain_fail'] = $params['sms_bargain_fail'];            }            if ($system['lottery'] == 1) {                $data['sms_lottery_new'] = $params['sms_lottery_new'];            }            if ($system['fenxiao'] == 1) {                if ($system['fenxiao06'] > 0 && $params['sms_worker'] == 1) {                    $data['sms_fenxiao06'] = $params['sms_fenxiao06'];                }                if ($system['selling_agent'] == 1) {                    $data['sms_comm_agent'] = $params['sms_comm_agent'];                }                if ($system['fenxiao01'] > 0) {                    $data['sms_fenxiao01'] = $params['sms_fenxiao01'];                }                if ($system['fenxiao01'] > 1) {                    $data['sms_fenxiao02'] = $params['sms_fenxiao02'];                }                if ($system['fenxiao01'] > 2) {                    $data['sms_fenxiao03'] = $params['sms_fenxiao03'];                }                if ($system['fenxiao05'] == 1) {                    $data['sms_fenxiao05'] = $params['sms_fenxiao05'];                }                if ($system['fenxiao08'] == 1) {                    $data['sms_fenxiao08'] = $params['sms_fenxiao08'];                }            }            //首次开启时间            if($has_sms_config['open_yx_sms']==0&&empty($has_sms_config['open_time'])&&$data['open_yx_sms']==1){                $data['open_time'] = date("Y-m-d H:i:s",time());                yxlog('群发短信首次开启时间:'.$data['open_time'],'短信配置编辑' );            }            if (!$has_sms_config) {                $data['themeid'] = $themeid;                $data['module_name'] = MODULE_NAME;                $res = $insertid = db_insert(t_sms_config, $data);                return $res;            } else {                //修改日志                $old_data = [];                $res = db_update(t_sms_config, $data, ['themeid' => $themeid, 'module_name' => MODULE_NAME, 'id' => $has_sms_config['id']]);                foreach ($data as $k => $v) {                    $old_data[$k] = $has_sms_config[$k];                }                writelog($themeid, '短信配置编辑', $old_data, $data, $_G['username']);                return $res;            }        }        return false;    }    /**     * Desc:获取已通过短信模版数量     * User:cbw     * Email:17854288794@163.com     * Time: 2023/3/16 10:14     * @param $themeid     * @return mixed     */    public static function getCanSendTemplateTotal($themeid, $module_name = MODULE_NAME)    {        $sql = " select count(*) as cnt from " . tablename(t_sms_template) . " where module_name='$module_name' and  themeid=$themeid and template_status=1";        return db_find($sql)['cnt'];    }    /**     * Desc:申请短信模版     * User:cbw     * Email:17854288794@163.com     * Time: 2023/2/25 13:27     * @param $TemplateType     * @param $TemplateName     * @param $TemplateContent     * @param $Remark     * @return array     */    public static function addSmsTemplate($TemplateType, $TemplateName, $TemplateContent, $Remark)    {        if (!$TemplateType) {            return ['status' => 0, 'msg' => '短信类型缺失'];        }        if (!$TemplateName) {            return ['status' => 0, 'msg' => '短信模版名称缺失'];        }        if (!$TemplateContent) {            return ['status' => 0, 'msg' => '短信模版内容缺失'];        }        if (!$Remark) {            return ['status' => 0, 'msg' => '短信模版使用场景描述缺失'];        }        $params["TemplateType"] = $TemplateType;        $params["TemplateName"] = $TemplateName;        $params["TemplateContent"] = $TemplateContent;        $params['Remark'] = $Remark;        $params['Action'] = 'AddSmsTemplate';        $params['RegionId'] = 'cn-hangzhou';        $params['Version'] = '2017-05-25';        $response = self::request($params);        if ($response['Code'] == 'OK') {            //todo  执行记录入库            $res = ['status' => 200, 'msg' => 'success', 'request_id' => $response['RequestId'], 'template_code' => $response['TemplateCode']];        } else {            $res = ['status' => $response['Code'], 'msg' => $response['Message'], 'request_id' => $response['RequestId'], 'template_code' => $response['TemplateCode']];        }        return $res;    }    /**     * Desc:修改未通过短信模版     * User:cbw     * Email:17854288794@163.com     * Time: 2023/2/25 13:31     * @param $TemplateType     * @param $TemplateName     * @param $TemplateCode     * @param $TemplateContent     * @param $Remark     * @return array     */    public static function editSmsTemplate($TemplateType, $TemplateName, $TemplateCode, $TemplateContent, $Remark)    {        if (!$TemplateType) {            return ['status' => 0, 'msg' => '短信类型缺失'];        }        if (!$TemplateName) {            return ['status' => 0, 'msg' => '短信模版名称缺失'];        }        if (!$TemplateCode) {            return ['status' => 0, 'msg' => '短信模版CODE缺失'];        }        if (!$TemplateContent) {            return ['status' => 0, 'msg' => '短信模版内容缺失'];        }        if (!$Remark) {            return ['status' => 0, 'msg' => '短信模版使用场景描述缺失'];        }        $params["TemplateType"] = $TemplateType;        $params["TemplateName"] = $TemplateName;        $params["TemplateCode"] = $TemplateCode;        $params["TemplateContent"] = $TemplateContent;        $params['Remark'] = $Remark;        $params['Action'] = 'ModifySmsTemplate';        $params['RegionId'] = 'cn-hangzhou';        $params['Version'] = '2017-05-25';        $response = self::request($params);        if ($response['Code'] == 'OK') {            //todo  执行记录入库            $res = ['status' => 200, 'msg' => 'success', 'request_id' => $response['RequestId'], 'template_code' => $response['TemplateCode']];        } else {            $res = ['status' => $response['Code'], 'msg' => $response['Message'], 'request_id' => $response['RequestId'], 'template_code' => $response['TemplateCode']];        }//        $res = ['status'=>200,'msg'=>'success','request_id'=>6666,'template_code'=>'88888'];        return $res;    }    /**     * Desc:创建签名     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 10:44     * @param $content     * @return mixed     */    public static function llSignCreate($content)    {        $post_url = 'https://apis.shlianlu.com/sms/product/sign/create';        $params = ['content' => $content];        $format_json = self::llFormatParams($params);        $res = self::llPostCurl($format_json, $post_url);        return $res;    }    /**     * Desc:获取签名列表     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 10:44     * @return mixed     */    public static function llSignGet()    {        $post_url = 'https://apis.shlianlu.com/sms/product/sign/get';        $params = [];        $format_json = self::llFormatParams($params);        $res = self::llPostCurl($format_json, $post_url);        return $res;    }    /**     * Desc:指定签名id删除     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 10:44     * @param $SignId     * @return mixed     */    public static function llSignDelete($SignId)    {        $post_url = 'https://apis.shlianlu.com/sms/product/sign/delete';        $params = ['SignId' => $SignId];        $format_json = self::llFormatParams($params);        $res = self::llPostCurl($format_json, $post_url);        return $res;    }    /**     * Desc:编辑短信模板     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 17:47     * @param $template_id     * @param $content     * @return mixed     */    public static function llTemplateUpdate($template_id, $content)    {        $post_url = 'https://apis.shlianlu.com/sms/product/template/update';        $params = ['TemplateId' => $template_id, 'content' => $content];        $format_json = self::llFormatParams($params);        $res = self::llPostCurl($format_json, $post_url);        return $res;    }    /**     * Desc:短信模板删除     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 17:52     * @param $template_id     * @return mixed     */    public static function llTemplateDelete($template_id)    {        $post_url = 'https://apis.shlianlu.com/sms/product/template/delete';        $params = ['TemplateId' => $template_id];        $format_json = self::llFormatParams($params);        $res = self::llPostCurl($format_json, $post_url);        return $res;    }    /**     * Desc:短信模板查询     * Author:cbw     * Email:17854288794@163.com     * Time: 2023/7/18 18:13     * @param $template_id     * @return mixed     */    public static function llTemplateGetById($template_id)    {        $post_url = 'https://api.shlianlu.com/sms/product/template/getById';        $params = ['TemplateId' => $template_id];        $format_json = self::llFormatParams($params);        $res = self::llPostCurl($format_json, $post_url);        return $res;    }    /**     * Desc:获取短信模版状态下的数量     * User:cbw     * Email:17854288794@163.com     * Time: 2023/2/25 14:33     * @param $themeid     * @return array[]     */    public static function getSmsTemplateStatusCount($themeid, $module_name = MODULE_NAME)    {        $first_arr = ['key' => -1, 'title' => '全部', 'total' => 0];        $arr = [            ['key' => 0, 'title' => '审核中', 'total' => 0],            ['key' => 1, 'title' => '审核通过', 'total' => 0],            ['key' => 2, 'title' => '审核未通过', 'total' => 0],        ];        foreach ($arr as $k => $v) {            $sql = " select count(*) as cnt from " . tablename(t_sms_template) . " where module_name='$module_name' and themeid=$themeid and template_status=" . $v['key'];            $arr[$k]['total'] += db_find($sql)['cnt'];            $first_arr['total'] += db_find($sql)['cnt'];        }        array_unshift($arr, $first_arr);        return $arr;    }    /**     * Desc:获取短信模版列表     * User:cbw     * Email:17854288794@163.com     * Time: 2023/2/25 14:49     * @param $themeid     * @param $search     * @param $page_start     * @param $page_size     * @param $status     * @param $type     * @param false $count     * @return int     */    public static function getSmsTemplate($themeid, $search, $page_start, $page_size, $status, $type, $count = false)    {        $module_name = MODULE_NAME;        $condition = "";        if ($search) {            $condition .= " AND out_template_name LIKE '" . $search . "'" . " or remark LIKE '" . $search . "'";        }        if ($status > 0) {            $condition .= " and template_status='$status'";        }        if ($type) {            $condition .= " and template_type='$type'";        }        $condition .= " order by created_at desc";        if ($page_size && !$count) {            $condition .= " LIMIT " . $page_start . "," . $page_size;        }        $sql = "  from " . tablename(t_sms_template) . "  where module_name ='$module_name' and themeid=$themeid " . $condition;        if ($count) {            return intval(db_fetchcolumn('SELECT COUNT(*)' . $sql));        } else {            $sql = " select * " . $sql;            return db_select($sql);        }    }    /************联麓信息*************/    /**     * Desc:通过短信模版id获取短信模版     * User:cbw     * Email:17854288794@163.com     * Time: 2023/3/17 20:46     * @param $themeid     * @param $template_id     * @param string $module_name     * @return mixed     */    public static function getSmsTemplateItem($themeid, $template_id, $module_name = MODULE_NAME)    {        return db_get(t_sms_template, ['themeid' => $themeid, 'id' => $template_id, 'module_name' => $module_name]);    }    /**     * Desc:插入快读模版中的记录手机号     * User:cbw     * Email:17854288794@163.com     * Time: 2023/3/17 13:23     * @param $data     * @return mixed     */    public static function addQuickMobile($data)    {        global $_G, $_P;        $sql = " insert into " . tablename(t_sms_quick_mobile) . " (template_id,mobile,themeid,admin_name,ip) values " . $data;        return db_find($sql);    }    /**     * Desc:获取模版下的手机号     * User:cbw     * Email:17854288794@163.com     * Time: 2023/3/17 14:31     * @param $themeid     * @param $template_id     * @return mixed     */    public static function getQuickMobileList($themeid, $template_id)    {        return db_getall(t_sms_quick_mobile, ['themeid' => $themeid, 'template_id' => $template_id]);    }    /**     * Desc:单个或批量查询短信模版审核状态     * User:cbw     * Email:17854288794@163.com     * Time: 2023/3/17 20:30     * @param $themeid     * @param $template_id     * @param false $query_all     * @param string $module_name     * @return array     */    public static function getQueryTemplateStatus($themeid, $template_id, $query_all = false, $module_name = MODULE_NAME)    {        if (!$query_all && $template_id) {            //单个查询            $item = db_get(t_sms_template, ['themeid' => $themeid, 'id' => $template_id, 'module_name' => $module_name]);            if ($item && $item['template_status'] == 0) {                $template_code = $item['template_code'];                $res = self::querySmsTemplate($template_code);                yxlog('短信模版状态查询：' . json_encode($res), '短信模版');                return $res;            }        } else {            //全部查询            $list = db_getall(t_sms_template, ['themeid' => $themeid, 'module_name' => $module_name, 'template_status' => 0]);            if ($list) {                foreach ($list as $k => $v) {                    $template_code = $v['template_code'];                    $res = self::querySmsTemplate($template_code);                    yxlog('短信模版状态查询：' . json_encode($res), '短信模版');                }            }        }    }    /**     * Desc:查询短信模版的审核状态     * User:cbw     * Email:17854288794@163.com     * Time: 2023/2/25 13:38     * @param $TemplateCode     * @return array     */    public static function querySmsTemplate($TemplateCode)    {        if (!$TemplateCode) {            return ['status' => 0, 'msg' => '短信模版CODE缺失'];        }        $params["TemplateCode"] = $TemplateCode;        $params['Action'] = 'QuerySmsTemplate';        $params['RegionId'] = 'cn-hangzhou';        $params['Version'] = '2017-05-25';        $response = self::request($params);        if ($response['Code'] == 'OK') {            //todo  执行记录入库            $res = [                'status' => 200,                'msg' => 'success',                'template_content' => $response['TemplateContent'],                'request_id' => $response['RequestId'],                'template_code' => $response['TemplateCode'],                'template_status' => $response['TemplateStatus'],                'template_type' => $response['TemplateType'],                'template_name' => $response['TemplateName'],                'create_date' => $response['CreateDate'],                'reason' => $response['Reason'],            ];        } else {            $res = [                'status' => $response['Code'],                'msg' => $response['Message'],                'template_content' => $response['TemplateContent'],                'request_id' => $response['RequestId'],                'template_code' => $response['TemplateCode'],                'template_status' => $response['TemplateStatus'],                'template_type' => $response['TemplateType'],                'template_name' => $response['TemplateName'],                'create_date' => $response['CreateDate'],                'reason' => $response['Reason'],            ];        }        return $res;    }    /**     * Desc:违规词检测     * User:cbw     * Email:17854288794@163.com     * Time: 2023/3/17 20:47     * @param $str     */    public static function checkStrSafe($string, $symbol = '')    {        $list = [            '色情', '赌博', '毒品', '党政', '法律', '维权', '众筹', '慈善', '募捐', '宗教', '迷信', '股票',            '留学', '移民', '面试', '招聘', '商标', '专利', '博彩', '贷款', '催款', '还款', '信用卡',            '投资', '理财', '中奖', '抽奖', '夺宝', '秒杀', '云购', 'A货', '整容', '烟酒', '交友',            '暴力', '恐吓', '皮草', '返现', '返利', '代开', '发票', '代理', '代办', '加群', 'QQ', 'qq',            '微信', '殡葬', '刷单', '拉新', '众包', 'POS', 'pos', '兑换', '红包', '涩情', '微信', '加V', '加v', '上门', '裸聊',            '盲盒', '砍价'        ];        $count = 0;  //违规词个数        $sensitiveWord = '';//违规次        $stringAfter = $string;      // 替换后的内容        $pattern = "/" . implode("|", $list) . "/i"; // 定义正则表达式        if (preg_match_all($pattern, $string, $matches)) { // 匹配到了结果            $patternList = $matches[0];     // 匹配到的数组            $count = count($patternList);            $sensitiveWord = implode(',', $patternList);    // 敏感词数组转字符串            //把匹配到的数组进行合并，替换使用            $replaceArray = array_combine($patternList, array_fill(0, count($patternList), $symbol));            $stringAfter = strtr($string, $replaceArray); //结果替换        }        $log = '';        if ($count == 0) {            $log .= "暂未匹配到敏感词！";        } else {//            $log .= "匹配到 [ {$count} ]个敏感词：[ {$sensitiveWord} ]<br/>"."替换后为：[ {$stringAfter} ]";            $log .= "匹配到 [ {$count} ]个敏感词：[ {$sensitiveWord} ] " . "请修改后重新提交审核";        }        return ['filter_word_count' => $count, 'filter_word_content' => $string, 'filter_word_log' => $log, 'replace_content' => $stringAfter];    }    /**     * Desc:大批量直接压入队列     * User:cbw     * Email:17854288794@163.com     * Time: 2023/5/17 17:39     * @param $system     * @param $themeid     * @param $mobile     * @param $template_code     * @param $template_id     * @param $template_params_arr     */    public static function pushSmsSendQueue($system, $themeid, $mobile, $template_code, $template_id, $template_params_arr = '')    {        global $_G;        $sign_name = '易宣';        if ($_G['companyname'] == '飞驰软件') {            $sign_name = '飞驰';        } elseif ($_G['companyname'] == '金策软件') {            $sign_name = '金策';        } elseif ($_G['companyname'] == '联登科技') {            $sign_name = '联登';        }        $mobile_arr = $mobile;        $sign_name_arr = [];        //批量发送        $template_item = db_get(t_sms_template, ['id' => $template_id]);        $admin_name = $template_item['admin_name'] ? $template_item['admin_name'] : '系统发送';        $ip = $template_item['ip'] ? $template_item['ip'] : '';        if ($_G['username']) {            $admin_name = (string)$_G['username'];            $ip = (string)$_G['clientip'];        }        foreach ($mobile_arr as $kk => $vv) {            //判断手机号跟模板id是否存在发送记录            $mobile_has_send_log = db_get(t_sms_send_log, ['mobile' => $vv, 'templateId' => $template_id, 'themeid' => $themeid]);            if ($mobile_has_send_log) {                yxlog('短信插入队列存在重复记录：手机号:' . $vv . ';模板id:' . $template_id, '短信队列');                continue;            }            $arguments = [];            $user_arguments = [];            if ($template_item['diy_template_params']) {                $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                foreach ($diy_temp_params_arr as $k => $v) {                    array_push($arguments, ['code' => $v]);                    $user_arguments[$v] = $template_params_arr[$kk][$v];                }            }            $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);            $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');            $send_sms_flag = self::getSmsContentFlag($sms_length);            $uid = 0;            $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $vv]);            if ($get_order_info) {                $uid = $get_order_info['uid'];            }            $tmp_arguments = json_encode($user_arguments, JSON_UNESCAPED_UNICODE);            $error_send_total = 0;            $queue_str .= " ('$uid','$vv','diy',$error_send_total,1,'$template_id','alisms','$tmp_arguments','$themeid','$admin_name','$ip'),";        }        if ($queue_str) {            $queue_str = rtrim($queue_str, ',');            $queue_log_sql = " insert into " . tablename(t_sms_wait_send_queue) . " (uid,mobile,type,try_num,status,templateId,server_code,des,themeid,admin_name,ip) values " . $queue_str;            yxlog('短信批量插入队列：' . $queue_log_sql, '批量短信');            db_find($queue_log_sql);            self::deleteRepeatSendQueue();        }    }    /**     * Desc:删除队列中待发送重复记录     * User:cbw     * Email:17854288794@163.com     * Time: 2023/6/21 13:59     * @return true     */    public static function deleteRepeatSendQueue()    {        //判断存在记录        $count_sql = ' select count(*) as cnt from ' . tablename(t_sms_wait_send_queue) . " where id>0 ";        $count_num = db_find($count_sql)['cnt'];        if ($count_num > 0) {            //查询重复记录            $sql = "select id from " . tablename(t_sms_wait_send_queue) . " a where (a.templateId,a.mobile) in " .                "(select templateId,mobile from " . tablename(t_sms_wait_send_queue) . " group by templateId,mobile having count(*) > 1) and id not in " .                " (select min(id) from " . tablename(t_sms_wait_send_queue) . " group by templateId,mobile having count(*)>1)";            $res = db_select($sql);            if ($res) {                $ids_arr = array_column($res, 'id');                $ids = implode(',', $ids_arr);                if ($ids) {                    //删除重复记录                    $delete_query = " delete from " . tablename(t_sms_wait_send_queue) . " where id in (" . $ids . " ) ";                    $res2 = db_query($delete_query);                    return true;                }            }        }        return true;    }    public static function sendSmsQueueByTemplateId($themeid, $system, $template_id)    {        $success_total = 0;        $fail_total = 0;        $template_item = db_get(t_sms_template, ['id' => $template_id, 'themeid' => $themeid]);        $limit = '0,100';        if ($template_item['type'] == 'quick') {            $limit = '0,100';        }        $sql1 = " select * from " . tablename(t_sms_wait_send_queue) . " where themeid=$themeid and server_code='alisms' and try_num<3 and templateId=$template_id limit " . $limit;        $res1 = db_select($sql1);        if ($res1) {            //获取当前列的值有哪些            $mobile_arr = [];            $ids = '';            $all_arguments = [];            $has_err = false;            $template_item = db_get(t_sms_template, ['id' => $template_id]);            foreach ($res1 as $k => $v) {                $mobile_has_send_log = db_get(t_sms_send_log, ['mobile' => $v['mobile'], 'templateId' => $template_id, 'themeid' => $themeid]);                if ($mobile_has_send_log) {                    yxlog('队列短信发送存在重复记录：手机号:' . $v['mobile'] . ';模板id:' . $template_id, '短信队列');                } else {                    if ($v['try_num'] < 3) {                        $item = $v;                        unset($item['status']);                        $user_arguments = json_decode($v['des'], true);                        $arguments = [];                        if ($template_item['diy_template_params']) {                            $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                            foreach ($diy_temp_params_arr as $k1 => $v1) {                                array_push($arguments, ['code' => $v1]);                            }                        }                        $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);                        $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');                        $send_sms_flag = self::getSmsContentFlag($sms_length);                        $can_send_sms = self::checkCanSendSms($themeid, $send_sms_flag);                        if (!$can_send_sms) {                            $res = ['status' => 0, 'msg' => '账户余额不足,无法抵扣短信费用'];                            yxlog($res, '短信发送失败');                            $has_err = true;                            break;                        }                        array_push($mobile_arr, $v['mobile']);                        array_push($all_arguments, $user_arguments);                        $tmp_id = $v['id'];                        $sql = " delete from " . tablename(t_sms_wait_send_queue) . " where themeid=$themeid and id='$tmp_id'";                        db_find($sql);                    } else {                        $tmp_id = $v['id'];                        $sql = " delete from " . tablename(t_sms_wait_send_queue) . " where themeid=$themeid and id='$tmp_id'";                        db_find($sql);                        $fail_total += 1;                    }                }            }            if ($has_err) {                return ['status' => 0, 'success_total' => $success_total, 'fail_total' => $fail_total];                die();            }            if ($mobile_arr) {                if (count($mobile_arr) == 1) {                    self::beforeAliSmsSend($system, $themeid, $mobile_arr, $template_item['template_code'], $template_item['id'], $all_arguments);                    $success_total += 1;                } else {                    self::beforeAliSmsSend($system, $themeid, $mobile_arr, $template_item['template_code'], $template_item['id'], $all_arguments);                    $success_total += count($mobile_arr);                }                return ['status' => 1, 'success_total' => $success_total, 'fail_total' => $fail_total];            }        }        return ['status' => 0, 'success_total' => $success_total, 'fail_total' => $fail_total];    }    public static function autoCheckSmsTemplate($module_name, $system, $template_code = '', $admin_name = '系统更新')    {        if ($template_code) {            $item = db_get(t_sms_template, ['template_code' => $template_code, 'module_name' => $module_name]);            //判断 如果数据库中不存在次模版 调用删除模版            if (!$item) {                $delete_old_item_ali = Sms::deleteSmsTemplate($template_code);                return true;            }            $themeid = $item['themeid'];            $res = Sms::getLlSmsTemplate($item['template_code']);            if ($res['status'] == 200) {                $log_data = [                    'template_code' => $item['template_code'],                    'request_params' => json_encode(['template_code' => $item['template_code']]),                    'response_params' => json_encode($res),                    'admin_name' => $admin_name,                    'themeid' => $themeid,                ];                if ($res['template_status'] == 0) {                } elseif ($res['data']['status'] == 1) {                    $log_data['type'] = 3;                    $log_data['des'] = '审核通过';                    Sms::addSmsTemplateLog($log_data);                    $where = ['themeid' => $themeid, 'id' => $item['id']];                    $data = ['request_id' => $res['request_id'], 'template_status' => 1, 'confirm_test_sms' => 2];                    db_update(t_sms_template, $data, $where);                    //批量发送//                    self::quickSmsSend($themeid,$system);                } elseif ($res['data']['status'] == 3) {                    $log_data['type'] = 4;                    $log_data['des'] = '审核未通过，原因：' . $res['reason'];                    Sms::addSmsTemplateLog($log_data);                    $where = ['themeid' => $themeid, 'id' => $item['id']];                    $data = ['request_id' => $res['request_id'], 'template_status' => 2];                    db_update(t_sms_template, $data, $where);                }            }        }        $items = db_getall(t_sms_template, ['template_status' => 0, 'module_name' => $module_name]);        foreach ($items as $k => $v) {            $themeid = $v['themeid'];            $res = Sms::getLlSmsTemplate($v['template_code']);            if ($res['status'] == 200) {                $log_data = [                    'template_code' => $v['template_code'],                    'request_params' => json_encode(['template_code' => $v['template_code']]),                    'response_params' => json_encode($res),                    'admin_name' => $admin_name,                    'themeid' => $themeid,                ];                if ($res['data']['status'] == 0) {                } elseif ($res['data']['status'] == 1) {                    $log_data['type'] = 3;                    $log_data['des'] = '审核通过';                    Sms::addSmsTemplateLog($log_data);                    $where = ['themeid' => $themeid, 'id' => $v['id']];                    $data = ['request_id' => $res['request_id'], 'template_status' => 1, 'confirm_test_sms' => 2];                    db_update(t_sms_template, $data, $where);                } elseif ($res['data']['status'] == 3) {                    $log_data['type'] = 4;                    $log_data['des'] = '审核未通过，原因：' . $res['data']['refuseReason'];                    Sms::addSmsTemplateLog($log_data);                    $where = ['themeid' => $themeid, 'id' => $v['id']];                    $data = ['request_id' => $res['request_id'], 'template_status' => 2];                    db_update(t_sms_template, $data, $where);                }            }        }    }    /**     * Desc:删除短信模版     * User:cbw     * Email:17854288794@163.com     * Time: 2023/2/25 15:52     * @param $TemplateCode     * @return array     */    public static function deleteSmsTemplate($TemplateCode)    {        if (!$TemplateCode) {            return ['status' => 0, 'msg' => '短信模版CODE缺失'];        }        $params["TemplateCode"] = $TemplateCode;        $params['Action'] = 'deleteSmsTemplate';        $params['RegionId'] = 'cn-hangzhou';        $params['Version'] = '2017-05-25';        $response = self::request($params);        if ($response['Code'] == 'OK') {            //todo  执行记录入库            $res = ['status' => 200, 'msg' => 'success', 'request_id' => $response['RequestId'], 'template_code' => $response['TemplateCode']];        } else {            $res = ['status' => $response['Code'], 'msg' => $response['Message'], 'request_id' => $response['RequestId'], 'template_code' => $response['TemplateCode']];        }        return $res;    }    /**     * Desc:联麓短信模版查询     * User:wyx     * @return array     */    public static function getLlSmsTemplate($TemplateId)    {        $post_url = 'https://api.shlianlu.com/sms/product/template/getById';        $params["TemplateId"] = $TemplateId;        $format_json = self::llFormatParams($params);        $response = self::llPostCurl($format_json, $post_url);        if ($response['message'] == 'success') {            $res = ['status' => 200, 'msg' => 'success', 'data' => $response['data']];        } else {            $res = ['status' => $response['status'], 'msg' => $response['message']];        }        return $res;    }    /**     * Desc:创建短信日志     * User:cbw     * Email:17854288794@163.com     * Time: 2023/2/25 14:04     * @param $data     * @return mixed     */    public static function addSmsTemplateLog($data)    {        return $insertid = db_insert(t_sms_template_log, $data);    }    /**     * Desc:快捷模版发送     * User:cbw     * Email:17854288794@163.com     * Time: 2023/5/16 18:31     * @param $themeid     * @param $system     * @param $template_id     */    public static function quickSmsSend($themeid, $system, $template_id = '')    {        $module_name = MODULE_NAME;        if (!$template_id) {            $test_template = db_get(t_sms_template, ['themeid' => $themeid, 'type' => 'quick', 'module_name' => $module_name,                'template_status' => 1, 'confirm_test_sms' => 2, 'send_all_mobile' => 0]);        } else {            $test_template = db_get(t_sms_template, ['themeid' => $themeid, 'type' => 'quick', 'module_name' => $module_name,                'template_status' => 1, 'confirm_test_sms' => 2, 'id' => $template_id]);        }        if ($test_template) {            $ids = '';            $mobile_list = db_getall(t_sms_quick_mobile, ['themeid' => $themeid, 'template_id' => $test_template['id']], [], '', [], [1, 100]);            $mobile_arr = [];            $template_param_arr = [];            foreach ($mobile_list as $k => $v) {                array_push($mobile_arr, $v['mobile']);                array_push($template_param_arr, []);                $ids .= $v['id'] . ',';            }            Sms::beforeAliSmsSend($system, $themeid, $mobile_arr, $test_template['template_code'], $test_template['id'], $template_param_arr);            $data = ['send_all_mobile' => 1];            $where = ['id' => $test_template['id']];            $res2 = db_update(t_sms_template, $data, $where);            $ids = rtrim($ids, ',');            $sql = " delete from " . tablename(t_sms_quick_mobile) . " where themeid=$themeid and id in ( " . $ids . " ) ";            $res3 = db_find($sql);            return ['status' => 1, 'success_total' => count($mobile_list), 'fail_total' => 0];        }        return ['status' => 0, 'success_total' => 0, 'fail_total' => 0];    }    /**     * Desc:删除快速发送记录表中的重复数据 手机号模版id相同的 只保留最小的记录     * User:cbw     * Email:17854288794@163.com     * Time: 2023/6/19 14:23     * @return true|void     */    public static function deleteRepeatQuickMobileItem()    {        //判断存在记录        $count_sql = ' select count(*) as cnt from ' . tablename(t_sms_quick_mobile) . " where id>0 ";        $count_num = db_find($count_sql)['cnt'];        if ($count_num > 0) {            //查询重复记录            $sql = "select id from " . tablename(t_sms_quick_mobile) . " a where (a.template_id,a.mobile) in " .                "(select template_id,mobile from " . tablename(t_sms_quick_mobile) . " group by template_id,mobile having count(*) > 1) and id not in " .                " (select min(id) from " . tablename(t_sms_quick_mobile) . " group by template_id,mobile having count(*)>1)";            $res = db_select($sql);            if ($res) {                $ids_arr = array_column($res, 'id');                $ids = implode(',', $ids_arr);                if ($ids) {                    //删除重复记录                    $delete_query = " delete from " . tablename(t_sms_quick_mobile) . " where id in (" . $ids . " ) ";                    $res2 = db_query($delete_query);                    return true;                }            }        }        return true;    }    /**     * Desc:联麓申请短信模版     * User:wyx     * @param $TemplateType     * @param $TemplateName     * @param $TemplateContent     * @param $Remark     * @return array     */    public static function addLlSmsTemplate($TemplateType, $TemplateName, $TemplateContent, $Remark)    {        $post_url = 'https://api.shlianlu.com/sms/product/template/create';        if (!$TemplateType) {            return ['status' => 0, 'msg' => '短信类型缺失'];        }        if (!$TemplateName) {            return ['status' => 0, 'msg' => '短信模版名称缺失'];        }        if (!$TemplateContent) {            return ['status' => 0, 'msg' => '短信模版内容缺失'];        }        if (!$Remark) {            return ['status' => 0, 'msg' => '短信模版使用场景描述缺失'];        }        $params["SignId"] = "72944";        $params["content"] = $TemplateContent;        $params["TemplateName"] = $TemplateName;        $format_json = self::llFormatParams($params);        $response = self::llPostCurl($format_json, $post_url);        if ($response['message'] == 'success') {            $res = ['status' => 200, 'msg' => 'success', 'request_id' => 0, 'template_code' => $response['TemplateId']];        } else {            $res = ['status' => $response['status'], 'msg' => $response['message'], 'request_id' => 0, 'template_code' => $response['TemplateId']];        }        return $res;    }    /**     * Desc:快捷模版发送     * User:cbw     * Email:17854288794@163.com     * Time: 2023/5/16 18:31     * @param $themeid     * @param $system     * @param $template_id     */    public static function quickLlSmsSend($themeid, $system, $template_id = '')    {        $module_name = MODULE_NAME;        if (!$template_id) {            $test_template = db_get(t_sms_template, ['themeid' => $themeid, 'type' => 'quick', 'module_name' => $module_name,                'template_status' => 1, 'confirm_test_sms' => 2, 'send_all_mobile' => 0]);        } else {            $test_template = db_get(t_sms_template, ['themeid' => $themeid, 'type' => 'quick', 'module_name' => $module_name,                'template_status' => 1, 'confirm_test_sms' => 2, 'id' => $template_id]);        }        if ($test_template) {            $ids = '';            $mobile_list = db_getall(t_sms_quick_mobile, ['themeid' => $themeid, 'template_id' => $test_template['id']], [], '', [], [1, 100]);            $mobile_arr = [];            $template_param_arr = [];            foreach ($mobile_list as $k => $v) {                array_push($mobile_arr, $v['mobile']);                array_push($template_param_arr, []);                $ids .= $v['id'] . ',';            }            Sms::beforeLlSmsSend($system, $themeid, $mobile_arr, $test_template['template_code'], $test_template['id'], $template_param_arr);            $data = ['send_all_mobile' => 1];            $where = ['id' => $test_template['id']];            $res2 = db_update(t_sms_template, $data, $where);            $ids = rtrim($ids, ',');            $sql = " delete from " . tablename(t_sms_quick_mobile) . " where themeid=$themeid and id in ( " . $ids . " ) ";            $res3 = db_find($sql);            return ['status' => 1, 'success_total' => count($mobile_list), 'fail_total' => 0];        }        return ['status' => 0, 'success_total' => 0, 'fail_total' => 0];    }    /**     * Desc:联麓发送短信 批量还是单个     * User:cbw     * Email:17854288794@163.com     * Time: 2023/3/21 13:14     * @param $system     * @param $themeid     * @param $mobile     * @param $template_code     * @param $template_id     * @param string $template_params_arr     */    public static function beforeLlSmsSend($system, $themeid, $mobile, $template_code, $template_id, $template_params_arr = '')    {        global $_G;        $sign_name = '易宣';        if ($_G['companyname'] =='飞驰软件'){            $sign_name = '飞驰';        }elseif ($_G['companyname'] =='金策软件'){            $sign_name = '金策';        }elseif ($_G['companyname'] =='联登科技'){            $sign_name = '联登';        }        $has_err = false;        $mobile_arr = $mobile;        $sign_name_arr = [];        //批量发送        $template_item = db_get(t_sms_template, ['id' => $template_id]);        $admin_name = $template_item['admin_name'] ? $template_item['admin_name'] : '系统发送';        $ip = $template_item['ip'] ? $template_item['ip'] : '';        if ($_G['username']) {            $admin_name = (string)$_G['username'];            $ip = (string)$_G['clientip'];        }        foreach ($mobile_arr as $kk => $vv) {            $arguments = [];            $user_arguments = [];            if ($template_item['diy_template_params']) {                $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                foreach ($diy_temp_params_arr as $k => $v) {                    array_push($arguments, ['code' => $v]);                    $user_arguments[$v] = $template_params_arr[$kk][$k];                }            }            $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);            $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');            $send_sms_flag = self::getSmsContentFlag($sms_length);//            $can_send_sms = self::checkCanSendSms($themeid,$send_sms_flag);//            if (!$can_send_sms){//                $res = ['status'=>0,'msg'=>'账户余额不足,无法抵扣短信费用'];//                yxlog($res,'短信发送失败');//                $has_err = true;//                break;//            }            //array_push($sign_name_arr,$sign_name);        }        if ($has_err) {            return;            die();        }        $response = self::llSmsSend($mobile_arr, $template_code, $template_params_arr, 0,'sales');        yxlog('联麓短信批量发送回执：' . json_encode($response), '短信模版');        if ($response['status'] != 200) {            //发送失败            $error_log_str = "";            $queue_str = "";            $error = self::getErrorMessage($response['status']);            $tmp_trade_id = isset($response['trade_id']) ? $response['trade_id'] : '';            $error_send_total = 0;            foreach ($mobile_arr as $kk => $vv) {                $arguments = [];                $user_arguments = [];                if ($template_item['diy_template_params']) {                    $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                    foreach ($diy_temp_params_arr as $k => $v) {                        array_push($arguments, ['code' => $v]);                        $user_arguments[$v] = $template_params_arr[$kk][$v];                    }                }                $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);                $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');                $send_sms_flag = self::getSmsContentFlag($sms_length);                $tmp_desc = $response['status'] . '-' . $error;                $uid = 0;                $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $vv]);                if ($get_order_info) {                    $uid = $get_order_info['uid'];                }                $error_log_str .= " ('$uid','$vv','diy',6,'$template_id','$tmp_trade_id','ERROR','$sms_item_content',$send_sms_flag,'$tmp_desc','$themeid','$admin_name','$ip'),";                $tmp_arguments = json_encode($user_arguments, JSON_UNESCAPED_UNICODE);                //获取发送失败次数                $sql = " select count(*) as cnt from " . tablename(t_sms_send_log) . " where mobile=$vv and status=2 and templateId=$template_id";                $error_send_total = db_find($sql)['cnt'];              //  $queue_str .= " ('$uid','$vv','diy',$error_send_total,1,'$template_id','alisms','$tmp_arguments','$themeid','$admin_name','$ip'),";            }            if ($error_log_str) {                $error_log_str = rtrim($error_log_str, ',');                $error_log_sql = " insert into " . tablename(t_sms_send_log) . " (uid,mobile,type,status,templateId,tradeId,trade_status,content,sms_num,des,themeid,admin_name,ip) values " . $error_log_str;                yxlog('短信批量插入失败：' . $error_log_sql, '批量短信');                db_find($error_log_sql);            }//            if ($queue_str) {//                $queue_str = rtrim($queue_str, ',');//                $queue_log_sql = " insert into " . tablename(t_sms_wait_send_queue) . " (uid,mobile,type,try_num,status,templateId,server_code,des,themeid,admin_name,ip) values " . $queue_str;//                yxlog('短信批量插入队列：' . $queue_log_sql, '批量短信');//                db_find($queue_log_sql);//            }        } else {            $success_log_str = "";            $flag_str = "";            $tmp_trade_id = isset($response['trade_id']) ? $response['trade_id'] : '';            foreach ($mobile_arr as $kk => $vv) {                $arguments = [];                $user_arguments = [];                if ($template_item['diy_template_params']) {                    $diy_temp_params_arr = explode(',', $template_item['diy_template_params']);                    foreach ($diy_temp_params_arr as $k => $v) {                        array_push($arguments, ['code' => $v]);                        $user_arguments[$v] = $template_params_arr[$kk][$v];                    }                }                $sms_item_content = self::formatContent($template_item['out_template_content'], $arguments, $user_arguments);                $sms_length = (int)mb_strlen($sms_item_content, 'UTF8');                $send_sms_flag = self::getSmsContentFlag($sms_length);                $tmp_arguments = json_encode($user_arguments, JSON_UNESCAPED_UNICODE);                $uid = 0;                $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $vv]);                if ($get_order_info) {                    $uid = $get_order_info['uid'];                }                //成功日志                $success_log_str .= " ('$uid','$vv','diy',1,'$template_id','$tmp_trade_id','UNKNOW','$sms_item_content',$send_sms_flag,'$themeid','$admin_name','$ip'),";                //记录日志                $flag_str .= " ('$uid','$vv','diy',1,'$template_id',$send_sms_flag,'$sms_item_content','$tmp_trade_id','$tmp_arguments','$themeid','$admin_name','$ip'),";            }        }        if ($success_log_str) {            $success_log_str = rtrim($success_log_str, ',');            $success_log_sql = " insert into " . tablename(t_sms_send_log) . " (uid,mobile,type,status,templateId,tradeId,trade_status,content,sms_num,themeid,admin_name,ip) values " . $success_log_str;            yxlog('短信批量插入成功' . $success_log_sql, '批量短信');            db_find($success_log_sql);        }        if ($flag_str) {            $flag_str = rtrim($flag_str, ',');            $flag_log_sql = " insert into " . tablename(t_sms_send_flag) . " (uid,mobile,type,status,templateId,sms_num,content,tradeId,des,themeid,admin_name,ip) values " . $flag_str;            yxlog('短信批量插入' . $flag_log_sql, '批量短信');            db_find($flag_log_sql);        }    }    public static function editLlSmsTemplate($TemplateType, $TemplateName, $TemplateCode, $TemplateContent, $Remark)    {        if (!$TemplateType) {            return ['status' => 0, 'msg' => '短信类型缺失'];        }        if (!$TemplateName) {            return ['status' => 0, 'msg' => '短信模版名称缺失'];        }        if (!$TemplateCode) {            return ['status' => 0, 'msg' => '短信模版CODE缺失'];        }        if (!$TemplateContent) {            return ['status' => 0, 'msg' => '短信模版内容缺失'];        }        if (!$Remark) {            return ['status' => 0, 'msg' => '短信模版使用场景描述缺失'];        }        $post_url = 'https://apis.shlianlu.com/sms/product/template/update';        $params["SignId"] = "72944";        $params["TemplateId"] = $TemplateCode;        $params["content"] = $TemplateContent;        $params["TemplateName"] = $TemplateName;        $format_json = self::llFormatParams($params);        $response = self::llPostCurl($format_json, $post_url);        if ($response['status'] == '00') {            $res = ['status' => 200, 'msg' => 'success', 'request_id' => 0, 'template_code' => $response['TemplateId']];        } else {            $res = ['status' => $response['status'], 'msg' => $response['message'], 'request_id' => 0, 'template_code' => $response['TemplateId']];        }        return $res;    }    /**     * Desc:联麓发送个性短信     * User:wyx     * Time: 2023/8/9 09:59     * @param $system     * @param $themeid     * @param $template_id     * @param $mobile     * @param $ContextParamSet     * @return array     */    public static function llPersonalSend($system,$config,$themeid,$template_content,$mobile,$ContextParamSet,$TaskTime,$type)    {        global $_G;        $sign_name = self::getSignature($system,$themeid);//        if ($_G['companyname'] =='飞驰软件'){//            $sign_name = '飞驰';//        }elseif ($_G['companyname'] =='金策软件'){//            $sign_name = '金策';//        }elseif ($_G['companyname'] =='联登科技'){//            $sign_name = '联登';//        }        $has_err = false;        $mobile_arr = $mobile;        $sign_name_arr = [];        if ($_G['username']) {            $admin_name = (string)$_G['username'];            $ip = (string)$_G['clientip'];        }        if (!$ContextParamSet) {            return ['status' => 0, 'msg' => '变量元素内容缺失'];        }        $reg = "/\{%[\s\S]*?%\}/";        preg_match_all($reg, $template_content, $arr);        $temp_code = $arr[0];        $has_url = false;        $url_key = 0;        $short_url = '';        if(in_array("{%活动网址%}", $temp_code)){            $has_url = true;            $url_key = array_search("{%活动网址%}", $temp_code);        }        $send_num = 0;        $has_err = false;        $res = '';        $recode_data = array();        foreach ($ContextParamSet  as $key=>$val){            $mobile = $val[0];            unset($val[0]);            $param = $val;            if($has_url){                if($system['softmode']>0) {  //小程序                    $path = '';                    $theme = Theme::getThemeById($themeid);                    $query = MODULE_NAME . "-" . $themeid . "-" . '0' . "-" . $theme['softkey'];                    $wx_link = self::getUrlLink($system, $path, $query);                    if ($wx_link['errcode'] == 0) {                        $wx_link = $wx_link['url_link'];                    }                    //todo  短链生成失败带处理                    $yx_link = Poster::GetMainUrl($system, $wx_link, MODULE_NAME . '用户' . '0' . '短信跳转');                    // $format_link = substr($yx_link, -6);                    $format_link = parse_url($yx_link);                    //    $sms_item_content = str_replace("{%活动网址%}",$format_link['host'].$format_link['path'], $sms_item_content);                    if ($format_link) {                        $short_url = $format_link['host'] . $format_link['path'];                    }                }else{     //h5直接跳转                    $indexurl = $config['indexurl'];                    if($indexurl){                        $indexurl_array = parse_url($indexurl);                        $short_url = $indexurl_array['host'].$indexurl_array['path'];                    }                }                array_splice($param, $url_key, 0, $short_url);                array_splice($ContextParamSet[$key], $url_key+1, 0, $short_url);            }            $sms_item_content = str_replace($temp_code,$param, $template_content);    //批量替换            $sms_length =  (int)mb_strlen($sms_item_content,'UTF8');            $send_sms_flag =  ceil($sms_length / 67);            $send_num= $send_num+$send_sms_flag;            $recode_data[] = [                'mobile' => $mobile,                'content' =>  $sms_item_content,                'sms_num' => $send_sms_flag            ];            $can_send_sms = self::checkCanSendSms($themeid,$send_num);            if (!$can_send_sms){                $res = ['status'=>0,'msg'=>'账户余额不足,无法抵扣短信费用'];                yxlog($res,'短信发送失败');                $has_err = true;                break;            }        }        if ($has_err){            return $res;            die();        }        $post_url = 'https://apis.shlianlu.com/sms/trade/personal/send';        $params["Type"] = "2";        $params["SignName"] = "【{$sign_name}】";        $params["SessionContextSet"] = $template_content;        $params["ContextParamSet"] = $ContextParamSet;        if($type=='notify'){            $params['SessionContextSet'] = str_replace("拒收请回复R", "", $params['SessionContextSet']);        }        if($TaskTime>0){            $params["TaskTime"] = $TaskTime;        }        $params["Tag"] = MODULE_NAME.'-'.$themeid;        yxlog('联麓短信批量发送：' . json_encode($params), '联麓个性短信');        $format_json = self::llFormatParams($params,$type);        $response = self::llPostCurl($format_json, $post_url);        yxlog('联麓短信批量发送回执：' . json_encode($response), '联麓个性短信');        $tmp_trade_id = isset($response['taskId']) ? $response['taskId'] : '';        if ($response['status'] != 200) {           //发送失败            $error_log_str = "";            //$queue_str = "";            $error = self::getErrorMessage($response['status']);            //$error_send_total = 0;            foreach ($recode_data as $kk => $vv) {                $mobile_num = $vv['mobile'];                $sms_item_content = $vv['content'];                $send_sms_flag = $vv['sms_num'];                $tmp_desc = $response['status'] . '-' . $error;                $uid = 0;                $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $mobile]);                if ($get_order_info) {                    $uid = $get_order_info['uid'];                }                $error_log_str .= " ('$uid','$mobile_num','senior','$type',6,0,'$tmp_trade_id','ERROR','$sms_item_content',$send_sms_flag,'$tmp_desc','$themeid','$admin_name','$ip','$TaskTime'),";            }            if ($error_log_str) {                $error_log_str = rtrim($error_log_str, ',');                $error_log_sql = " insert into " . tablename(t_sms_send_log) . " (uid,mobile,type,templateKey,status,templateId,tradeId,trade_status,content,sms_num,des,themeid,admin_name,ip,fixed_time) values " . $error_log_str;//                yxlog('短信批量插入失败：' . $error_log_sql, '批量短信');                db_find($error_log_sql);            }        } else {            $success_log_str = "";            $flag_str = "";            $tmp_trade_id = isset($response['taskId']) ? $response['taskId'] : '';            foreach ($recode_data as $kk => $vv) {                $mobile_num = $vv['mobile'];                $sms_item_content = $vv['content'];                $send_sms_flag = $vv['sms_num'];                $tmp_arguments = json_encode($temp_code, JSON_UNESCAPED_UNICODE);                $uid = 0;                $get_order_info = db_get(t_record, ['themeid' => $themeid, 'mobile' => $mobile_num]);                if ($get_order_info) {                    $uid = $get_order_info['uid'];                }                //成功日志                $success_log_str .= " ('$uid','$mobile_num','senior','$type',6,'0','$tmp_trade_id','UNKNOW','$sms_item_content',$send_sms_flag,'$themeid','$admin_name','$ip','$TaskTime'),";                //记录日志                $flag_str .= " ('$uid','$mobile_num','senior','$type',6,'0',$send_sms_flag,'$sms_item_content','$tmp_trade_id','$tmp_arguments','$themeid','$admin_name','$ip'),";            }        }        if ($success_log_str) {            $success_log_str = rtrim($success_log_str, ',');            $success_log_sql = " insert into " . tablename(t_sms_send_log) . " (uid,mobile,type,templateKey,status,templateId,tradeId,trade_status,content,sms_num,themeid,admin_name,ip,fixed_time) values " . $success_log_str;            yxlog('短信批量插入成功' . $success_log_sql, '批量短信');            db_find($success_log_sql);        }        if ($flag_str) {            $flag_str = rtrim($flag_str, ',');            $flag_log_sql = " insert into " . tablename(t_sms_send_flag) . " (uid,mobile,type,templateKey,status,templateId,sms_num,content,tradeId,des,themeid,admin_name,ip) values " . $flag_str;            yxlog('短信批量插入' . $flag_log_sql, '批量短信');            db_find($flag_log_sql);        }        if ($response['status'] == '00') {            $res = ['status' => 200, 'msg' => 'success', 'request_id' => $response['taskId']];        } else {            $res = ['status' => $response['status'], 'msg' => $response['message'], 'request_id' => $response['taskId']];        }        return $res;    }    //余额查询接口    public static function productBbalance()    {        $post_url = 'https://apis.shlianlu.com/sms/product/balance';        $params = [];        $format_json = self::llFormatParams($params);        $response = self::llPostCurl($format_json, $post_url);        if ($response['status'] == '00') {            $res = ['status' => 200, 'msg' => 'success', 'request_id' => 0, 'template_code' => $response['TemplateId']];        } else {            $res = ['status' => $response['status'], 'msg' => $response['message'], 'request_id' => 0, 'template_code' => $response['TemplateId']];        }        return $res;    }    /**     * Desc:安装sql     * User:cbw     * Email:17854288794@163.com     * Time: 2022/12/6 17:47     */    public function installSql()    {        $sql = "            CREATE TABLE IF NOT EXISTS `yx_" . MODULE_NAME . "_sms_send_flag` (                `id` int(11) not null AUTO_INCREMENT,                `uid` int(11) not null default 0 comment '用户uid',                `mobile` varchar(11) not null default 0 comment '手机号',                `type` varchar(64) not null default '' comment '场景值',                `status` tinyint(1)  not null default 1 comment '状态  1已发送 3发送成功 4发送失败',                `templateId` text   comment '短信模版Id',                `templateKey` text   comment '短信模版KEY',                `sms_num` int(4) not null DEFAULT 1 comment '短信内容扣除短信条数',                `content` text   comment '发送内容',                `tradeId` text   comment '回执id',                `des` text   comment '备注',                `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',                `admin_name` varchar(64) not null default '' comment '操作人',                `ip` varchar(128) not null default '' comment '操作人ip',                `themeid` varchar(11) not null default '' comment '活动id',                PRIMARY KEY (`id`)                )ENGINE = InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='活动短信发送记录表';                                CREATE TABLE IF NOT EXISTS `yx_" . MODULE_NAME . "_sms_wait_send_queue` (                `id` int(11) not null AUTO_INCREMENT,                `uid` int(11) not null default 0 comment '用户uid',                `mobile` varchar(11) not null default 0 comment '手机号',                `type` varchar(64) not null default '' comment '场景值',                `from` int(4) not null default 1 comment '来源 1系统添加 2手动添加',                `try_num` int(4) not null default 0 comment '尝试次数 默认0',                `status` tinyint(1)  not null default 1 comment '状态  1等待 2完成 5等待，失败压入',                `server_code` varchar(11) not null default 'gt' comment '短信服务商 gt alisms',                `templateId` text   comment '短信模版Id',                `templateKey` text   comment '短信模版KEY',                `content` text   comment '发送内容',                `des` text   comment '备注',                `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',                `admin_name` varchar(64) not null default '' comment '操作人',                `ip` varchar(128) not null default '' comment '操作人ip',                `themeid` varchar(11) not null default '' comment '活动id',                PRIMARY KEY (`id`)                )ENGINE = InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='活动短信待发送队列表';                                CREATE TABLE IF NOT EXISTS `yx_" . MODULE_NAME . "_sms_send_log` (                `id` int(11) not null AUTO_INCREMENT,                `uid` int(11) not null default 0 comment '用户uid',                `mobile` varchar(11) not null default 0 comment '手机号',                `type` varchar(64) not null default '' comment '场景值',                `status` tinyint(1)  not null default 1 comment '状态  1成功 2失败 3未知',                `templateId` text   comment '短信模版Id',                `templateKey` text   comment '短信模版KEY',                `sms_num` int(4) not null DEFAULT 1 comment '短信内容扣除短信条数',                `tradeId` text   comment '回执id',                `trade_status` varchar(64) not null default ''   comment '回执状态',                `trade_info` text   comment '回执内容',                `content` text   comment '发送内容',                `des` text   comment '备注',                `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',                `admin_name` varchar(64) not null default '' comment '操作人',                `ip` varchar(128) not null default '' comment '操作人ip',                `themeid` varchar(11) not null default '' comment '活动id',                PRIMARY KEY (`id`)                )ENGINE = InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='活动短信发送日志';                                CREATE TABLE IF NOT EXISTS `yx_000_sms_template_log` (                `id` int(11) not null AUTO_INCREMENT,                `type` tinyint(3) not null default 1 comment '日志类型 1创建 2修改 3查询审核成功 4查询审核失败',                `template_code` text   comment '短信模版code',                `request_params` longtext   comment '请求参数',                `response_params` longtext   comment '返回参数',                `des` text   comment '备注',                `admin_name` varchar(64) not null default ''   comment '操作人',                `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',                `ip` varchar(128) not null default '' comment '操作人ip',                `themeid` varchar(11) not null default '' comment '活动id',                PRIMARY KEY (`id`)                )ENGINE = InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='活动短信模版操作日志';                                CREATE TABLE IF NOT EXISTS `yx_000_sms_template` (                `id` int(11) not null AUTO_INCREMENT,                `module_name` varchar(10) not null default '' comment '后台编号',                `template_type` int(11) not null default 0 comment '短信类型 0验证码1短信通知2推广短信',                `template_name` varchar(64) not null default '' comment '短信模版名称',                `out_template_name` varchar(64) not null default '' comment '展示短信模版名称',                `template_content` text comment '短信模版内容',                `out_template_content` text comment '展示短信模版内容',                `diy_template_params` text comment '动态值json',                `show_template_params` text comment '展示参数值',                `remark` text comment '短信模版申请说明',                `template_code` varchar(128) not null default ''  comment '短信模版code',                `request_id` text   comment '当前请求id',                `type` varchar(64) not null default 'default' comment '应用内短信类型 default默认 quick快捷模版',                `template_status` int(11) not null default 0   comment '模版审核状态 0审核中1通过2未通过10取消审核',                `send_all_mobile` tinyint(1)  not null default 0 comment '快捷模版发送状态 0未发送 1已发送',                `confirm_test_sms` tinyint(1)  not null default 0 comment '快捷模版测试  0未测试 1已测试未确认 2已测试已确认',                `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',                `admin_name` varchar(64) not null default '' comment '操作人',                `ip` varchar(128) not null default '' comment '操作人ip',                `themeid` varchar(11) not null default '' comment '活动id',                PRIMARY KEY (`id`)                )ENGINE = InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='活动短信模版';                                CREATE TABLE IF NOT EXISTS `yx_000_sms_quick_mobile` (                `id` int(11) not null AUTO_INCREMENT,                `template_id` varchar(64) not null default '' comment '模版编号',                `mobile` varchar(11) not null default '' comment '待发送手机号',                `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',                `admin_name` varchar(64) not null default '' comment '操作人',                `ip` varchar(128) not null default '' comment '操作人ip',                `themeid` varchar(11) not null default '' comment '活动id',                PRIMARY KEY (`id`)                )ENGINE = InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='活动短信快捷模版手机号记录';                                CREATE TABLE IF NOT EXISTS `yx_000_sms_config` (                `id` int(11) not null AUTO_INCREMENT,                `module_name` varchar(10) not null default '' comment '后台编号',                `open_yx_sms` int(4) not null default 0 comment '短信总开关',                `sms_user_pause` int(4) not null default 5 comment '暂停短信通知',                `sms_day_max` int(4) not null default 5 comment '每日最多发放',                `sms_hour_max` int(4) not null default 5 comment '每小时最多发放',                `sms_notice_signname` varchar(64) not null default '' comment '短信通知名称',                `sms_worker` int(4) not null default 0 comment '员工通知',                `sms_self_buy` int(4) not null default 0 comment '客户支付成功',                `sms_self_buy_tips` varchar(64) not null default '' comment '客户支付成功-提示语',                `sms_friend_help` int(4) not null default 0 comment '好友助力',                `sms_friend_help_success` int(4) not null default 0 comment '好友助力成功',                `sms_friend_buy` int(4) not null default 0 comment '好友购买',                `sms_friend_newfans` int(4) not null default 0 comment '好友到访',                `sms_mystery_boxes_new` int(4) not null default 0 comment '新盲盒可拆',                `sms_pintuan_new` int(4) not null default 0 comment '拼团-新成员通知',                `sms_pintuan_success` int(4) not null default 0 comment '拼团-拼团成功',                `sms_presale` int(4) not null default 0 comment '预售-补款通知',                `sms_currency` int(4) not null default 0 comment '0未开启，1活动开抢提醒，2到店通知，3未到店激活提醒',                `sms_bargain_help` int(4) not null default 0 comment '帮砍提醒',                `sms_bargain_success` int(4) not null default 0 comment '砍价成功',                `sms_bargain_fail` int(4) not null default 0 comment '砍价失败',                `sms_lottery_new` int(4) not null default 0 comment '抽奖机会增加',                `sms_fenxiao06` int(4) not null default 0 comment '分销通知-员工提成',                `sms_comm_agent` int(4) not null default 0 comment '分销通知-代理提成',                `sms_fenxiao01` int(4) not null default 0 comment '分销通知-一级分销',                `sms_fenxiao02` int(4) not null default 0 comment '分销通知-二级分销',                `sms_fenxiao03` int(4) not null default 0 comment '分销通知-三级分销',                `sms_fenxiao05` int(4) not null default 0 comment '分销通知-阅读红包',                `sms_fenxiao08` int(4) not null default 0 comment '分销通知-额外红包',                `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',                `admin_name` varchar(64) not null default '' comment '操作人',                `ip` varchar(128) not null default '' comment '操作人ip',                `themeid` varchar(11) not null default '' comment '活动id',                PRIMARY KEY (`id`)                )ENGINE = InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='活动短信配置';                                CREATE TABLE IF NOT EXISTS `yx_000_sms_sign` (                `id` int(11) not null AUTO_INCREMENT,                `content` varchar(64) not null default '' comment '签名内容',                `SignId` varchar(64) not null default '' comment '签名id',                `status` tinyint(1)  not null default 2 comment '状态  1审核通过 2待审核 3驳回',                `created_at` timestamp default CURRENT_TIMESTAMP comment '创建时间',                `admin_name` varchar(64) not null default '' comment '操作人',                `ip` varchar(128) not null default '' comment '操作人ip',                `module_name` varchar(10) not null default '' comment '后台编号',                `themeid` varchar(11) not null default '' comment '活动id',                PRIMARY KEY (`id`)                )ENGINE = InnoDB DEFAULT CHARACTER SET =utf8 COMMENT='活动短信签名记录';             ";         if(DOMAIN1 == "www.yixuan.net"){               $sql .= "CREATE TABLE IF NOT EXISTS `yx_" . MODULE_NAME . "_sms_amount_record` (                  `id` int(11) NOT NULL AUTO_INCREMENT,                  `type` tinyint(1) NOT NULL COMMENT '类型 1充值 2消费 3提现',                  `amount` decimal(8,2) NOT NULL COMMENT '金额变化',                  `balance` decimal(8,2) NOT NULL COMMENT '余额',                  `remark` varchar(300) DEFAULT NULL COMMENT '备注',                  `img` varchar(300) DEFAULT NULL COMMENT '充值或者提现截图',                  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',                  `themeid` int(11) NOT NULL COMMENT '活动id',                  `admin_name` varchar(64) NOT NULL DEFAULT '' COMMENT '操作人',                  `ip` varchar(64) NOT NULL DEFAULT '' COMMENT '操作人ip',                  `balance_old` decimal(8,2) NOT NULL DEFAULT '0.00' COMMENT '变化前余额',                  PRIMARY KEY (`id`)                   ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='对接服务器短信金额充值消费记录表\n'";        }        db_run($sql);        if (!db_fieldexists(MODULE_NAME . '_sms_send_flag', 'admin_name')) {            $sql = "ALTER TABLE `yx_" . MODULE_NAME . "_sms_send_flag` ADD COLUMN `admin_name` varchar(64) not null default '' comment '操作人';";            db_query($sql);        }        if (!db_fieldexists(MODULE_NAME . '_sms_send_flag', 'ip')) {            $sql = "ALTER TABLE `yx_" . MODULE_NAME . "_sms_send_flag` ADD COLUMN `ip` varchar(128) not null default '' comment '操作人ip';";            db_query($sql);        }        if (!db_fieldexists(MODULE_NAME . '_sms_wait_send_queue', 'admin_name')) {            $sql = "ALTER TABLE `yx_" . MODULE_NAME . "_sms_wait_send_queue` ADD COLUMN `admin_name` varchar(64) not null default '' comment '操作人';";            db_query($sql);        }        if (!db_fieldexists(MODULE_NAME . '_sms_wait_send_queue', 'ip')) {            $sql = "ALTER TABLE `yx_" . MODULE_NAME . "_sms_wait_send_queue` ADD COLUMN `ip` varchar(128) not null default '' comment '操作人ip';";            db_query($sql);        }        if (!db_fieldexists(MODULE_NAME . '_sms_send_log', 'admin_name')) {            $sql = "ALTER TABLE `yx_" . MODULE_NAME . "_sms_send_log` ADD COLUMN `admin_name` varchar(64) not null default '' comment '操作人';";            db_query($sql);        }        if (!db_fieldexists(MODULE_NAME . '_sms_send_log', 'ip')) {            $sql = "ALTER TABLE `yx_" . MODULE_NAME . "_sms_send_log` ADD COLUMN `ip` varchar(128) not null default '' comment '操作人ip';";            db_query($sql);        }        if (!db_fieldexists(MODULE_NAME . '_sms_wait_send_queue', 'server_code')) {            $sql = "ALTER TABLE `yx_" . MODULE_NAME . "_sms_wait_send_queue` ADD COLUMN `server_code` varchar(11) not null default 'gt' comment '短信服务商 gt alisms';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'module_name')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `module_name` varchar(10) not null default '' comment '后台编号';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'out_template_content')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `out_template_content` text comment '展示短信模版内容';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'diy_template_params')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `diy_template_params` text comment '动态值json';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'show_template_params')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `show_template_params` text comment '展示参数值';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'type')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `type` varchar(64) not null default 'default' comment '应用内短信类型 default默认 quick快捷模版';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'send_all_mobile')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `send_all_mobile` tinyint(1)  not null default 0 comment '快捷模版发送状态 0未发送 1已发送';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'confirm_test_sms')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `confirm_test_sms` tinyint(1)  not null default 0 comment '快捷模版测试  0未测试 1已测试未确认 2已测试已确认';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'admin_name')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `admin_name` varchar(64) not null default '' comment '操作人';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template', 'ip')) {            $sql = "ALTER TABLE `yx_000_sms_template` ADD COLUMN `ip` varchar(128) not null default '' comment '操作人ip';";            db_query($sql);        }        if (!db_fieldexists('000_sms_template_log', 'ip')) {            $sql = "ALTER TABLE `yx_000_sms_template_log` ADD COLUMN `ip` varchar(128) not null default '' comment '操作人ip';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_fenxiao01_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_fenxiao01_tips` varchar(64) not null default '' comment '分销一级提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_fenxiao02_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_fenxiao02_tips` varchar(64) not null default '' comment '分销二级提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_fenxiao03_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_fenxiao03_tips` varchar(64) not null default '' comment '分销三级提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_fenxiao05_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_fenxiao05_tips` varchar(64) not null default '' comment '阅读红包提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_fenxiao06_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_fenxiao06_tips` varchar(64) not null default '' comment '抽奖机会提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_fenxiao08_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_fenxiao08_tips` varchar(64) not null default '' comment '额外红包提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_friend_buy_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_friend_buy_tips` varchar(64) not null default '' comment '好友购买提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_friend_newfans_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_friend_newfans_tips` varchar(64) not null default '' comment '好友到访提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_pintuan_new_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_pintuan_new_tips` varchar(64) not null default '' comment '拼团新成员提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_pintuan_success_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_pintuan_success_tips` varchar(64) not null default '' comment '拼团成功提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_presale_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_presale_tips` varchar(64)not null default '' comment '预售提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'sms_comm_agent_tips')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `sms_comm_agent_tips` varchar(64)not null default '' comment '代理提成提示';";            db_query($sql);        }        if (!db_fieldexists('000_sms_config', 'open_time')) {            $sql = "ALTER  TABLE `yx_000_sms_config` ADD  `open_time` varchar(64)not null default '' comment '首次开启时间';";            db_query($sql);        }        if (!db_fieldexists(MODULE_NAME . '_sms_send_log', 'fixed_time')) {            $sql = "ALTER TABLE `yx_" . MODULE_NAME . "_sms_send_log` ADD COLUMN `fixed_time` bigint(13) not null default 0 comment '定时发送时间';";            db_query($sql);        }    }    /**     * Desc:联麓通用模板     * User: mf     * Email:     * Time: 2023/8/3 14:12     * @param $key     * @return array     */    public static function llCurrency($key)    {        $array = [            '易宣' => [                [                    'id' => '70030234',                    'text' => '尊敬的客户{%text%}拒收请回复R',                ],            ],            '金策' => [                [                    'id' => '70030772',                    'text' => '尊敬的客户{%text%}拒收请回复R',                ],            ],            '飞驰' => [                [                    'id' => '70030773',                    'text' => '尊敬的客户{%text%}拒收请回复R',                ],            ],            '联登' => [                [                    'id' => '70030774',                    'text' => '尊敬的客户{%text%}拒收请回复R',                ],            ],            '领泽' => [                [                    'id' => '70030775',                    'text' => '尊敬的客户{%text%}拒收请回复R',                ],            ],        ];        return $array[$key];    }    /**     * Desc:yyyy-MM-dd HH:mm:ss转换13位时间戳     * User: mf     * Email:     * Time: 2023/8/9 11:14     * @param $time     * @return float|int     */    public static function timeStamp13($time)    {        $fixed_time = strtotime($time);        $fixed_time_13 = $fixed_time * 1000;        return $fixed_time_13;    }    /**     * Desc:匹配手机号     * User: mf     * Email:     * Time: 2023/8/18 16:08     * @param $mobile_type     * @param $mobile_type_type     * @param $start_time     * @param $end_time     * @return null     */    public static function filteratePhone ($config,$themeid,$mobile_type,$mobile_type_type,$start_time='',$end_time='')    {        if ($mobile_type_type=='default'){            if ($mobile_type==1){                //已支付+线下订单                $sql = " from ".tablename(t_record).                    " where themeid='$themeid' and (status=1 or status=3)   ";//                and addtime between " .$start_time." and ".$end_time;            }elseif ($mobile_type==2){                //未支付                $sql = " from ".tablename(t_record).                    " where themeid='$themeid' and status=0   ";//                and addtime between " .$start_time." and ".$end_time;            }elseif ($mobile_type==3){                //所有团长                $sql = "  from ".tablename(t_record).                    " where themeid='$themeid' and (status=1 or status=3)  and type=0 ";//                and addtime between " .$start_time." and ".$end_time;            }elseif ($mobile_type==4){                //所有团员                $sql = "  from ".tablename(t_record).                    " where themeid='$themeid' and (status=1 or status=3)  and type=1 ";//                and addtime between " .$start_time." and ".$end_time;            }elseif ($mobile_type==5){                //拼团成功的团长                $sql = "  from ".tablename(t_record).                    " where themeid='$themeid' and (status=1 or status=-2) and isfinish=1  and type=0 ";//                and addtime between " .$start_time." and ".$end_time;            }elseif ($mobile_type==6){                //拼团成功的团员                $sql = "  from ".tablename(t_record).                    " where themeid='$themeid' and (status=1 or status=-2) and isfinish=1  and type=1 ";//                and addtime between " .$start_time." and ".$end_time;            }elseif ($mobile_type==7){                //拼团中的团长                $sql = "  from ".tablename(t_record).                    " where themeid='$themeid' and (status=1 or status=-2) and isfinish=0  and type=0 ";//                and addtime between " .$start_time." and ".$end_time;            }elseif ($mobile_type==8){                //拼团中的团员                $sql = "  from ".tablename(t_record).                    " where themeid='$themeid' and (status=1 or status=-2) and isfinish=0  and type=1 ";//                and addtime between " .$start_time." and ".$end_time;            }            $total = db_find('select count(*) as cnt '.$sql)['cnt'];            $mobile_arr = db_select('select mobile '.$sql);        }else{            if ($mobile_type=='wait_hexiao'){                //未核销的手机号                $child_sql = " select order_id from ".tablename(t_hexiao)." as b where b.themeid=$themeid";                $sql = "from ".tablename(t_record)." where status>0 and isrefund=0 and id not in ( ". $child_sql." );";                $total = db_find(" select count(*) as cnt ".$sql)['cnt'];                $mobile_arr = db_select(" select mobile ".$sql);            }elseif($mobile_type=='has_hexiao'){                //已核销的手机号                $child_sql = " select order_id from ".tablename(t_hexiao)." as b where b.themeid=$themeid";                $sql = "from ".tablename(t_record)." where status>0 and isrefund=0 and id in ( ". $child_sql." );";                $total = db_find(" select count(*) as cnt ".$sql)['cnt'];                $mobile_arr = db_select(" select mobile ".$sql);            }elseif($mobile_type=='wait_active_customer'){                //客资手机号                $sql = " from ". tablename ( t_fans ) . " as f left join `yx_mc_members` as m on f.uid = m.uid WHERE f.themeid = '{$themeid}' and f.username='' and f.mobile!=' ' and f.nickname!='微信用户'";                $total = (int)db_find( "SELECT COUNT(*) as cnt " . $sql)['cnt'];                $mobile_arr = db_select(" select f.mobile ".$sql);            }else{                if (strstr($mobile_type,'address')){                    $key = substr($mobile_type,strpos($mobile_type,'_')+1);                    $key = $config['addressoptions'][$key];                    $sql = "   from ".tablename(t_record).                        " where themeid='$themeid' and (status=1 or status=3) and address='$key' ";//                and  addtime between " .$start_time." and ".$end_time;                }elseif (strstr($mobile_type,'formtwo')){                    $key = substr($mobile_type,strpos($mobile_type,'_')+1);                    $key = $config['formtwooptions'][$key];                    $sql = "  from ".tablename(t_record).                        " where themeid='$themeid' and (status=1 or status=3)  and formtwo='$key' ";//                and  addtime between " .$start_time." and ".$end_time;                }elseif (strstr($mobile_type,'shops')){                    $key = substr($mobile_type,strpos($mobile_type,'_')+1);                    $key = $config['options'][$key];                    $sql = "   from ".tablename(t_record).                        " where themeid='$themeid' and (status=1 or status=3)  and `option`='$key' ";//                and  addtime between " .$start_time." and ".$end_time;                }                $total = db_find("select count(*) as cnt ".$sql)['cnt'];                $mobile_arr = db_select("select mobile ".$sql);            }        }        $mobile_arr = array_values(array_column($mobile_arr,NULL,'mobile'));        $total = 0;        $mobile_txt = "";        foreach ($mobile_arr as $k => $v){            if ($v['mobile']){                $total+=1;                $mobile_txt .= $v['mobile'].PHP_EOL;            }        }        $response = ['total'=>$total,'mobile_txt'=>$mobile_txt];        return $response;    }    /**     * 获取当前的余额     */     public static function getBlance($themeid){          $balabnce_sql =  db_find("select balance from ".tablename(t_sms_amount_record)." where themeid = {$themeid}  order by id desc");          if($balabnce_sql){                return $balabnce_sql['balance'];          }else{                return 0;          }     }    /**     *添加金额变化记录     */     public static function addAmountRecord($themeid,$type,$amount,$remark='',$img='')     {         global $_G;         $admin_name = (string)$_G['username'];         if (!$admin_name){             $admin_name = '来自系统';         }         $ip = (string)$_G['clientip'];         $last_balance = self::getAmountRecordTotal($themeid);         if($type==3){             $str = '提现';             if($last_balance<=0){                 $res = ['status' =>0, 'msg' =>'余额不足'.$str.'失败'];                 return $res;                 exit;             }             $now_balance = $last_balance -  $amount;             if($now_balance<0){                 $res = ['status' =>0, 'msg' =>'余额不足'.$str.'失败'];                 return $res;                 exit();             }             $amount = $amount*-1;         }elseif($type==1){   //充值             $now_balance = $last_balance+$amount;         }         $insert_data = [             'themeid' => $themeid,             'type' => $type,             'amount' => $amount,             'balance' => $now_balance,             'remark' => $remark,             'img' => $img,             'balance_old' => $last_balance,             'admin_name'=>$admin_name,             'ip'=>$ip,             'created_at'=>date("Y-m-d H:i:s",time())         ];         $add = $insertid = db_insert(t_sms_amount_record, $insert_data);         if($add){             $res = ['status' => 200, 'msg' => '成功'];         }else{             $res = ['status' => 0, 'msg' => '失败'];         }         return $res;     }    /**     * Desc:获取可用余额     * Author:cbw     * Time: 2023/9/3 16:59     * @param $themeid     * @return mixed     */     public static function getAmountRecordTotal($themeid)     {         $sql = " select sum(amount) as amount_total from ".tablename(t_sms_amount_record)." where themeid='$themeid'";         $fetch = db_find($sql);        //查询已消费的短信条数（发送成功、发送中）         $sql2 = " select sum(sms_num) as cnt from " . tablename(t_sms_send_log) . " where themeid=$themeid  and (status=1 or status=6) ";         $used_sms = db_find($sql2)['cnt']*0.1;         $fetch_total = floatval($fetch['amount_total']);         $amount_total = bcsub($fetch_total,$used_sms,1);         return $amount_total;     }    /**     * Desc:联麓短信通知转营销     * User: mf     * Time: 2024/1/11 11:19     * @param $system     * @param $themeid     * @param $input     * @return false|void     */    public static function changeMarketing($system,$themeid,$input){        $bohui_taskid = $input['taskId'];        $llsms_taskid_sql = "            CREATE TABLE IF NOT EXISTS `yx_000_llsms_taskid` (                `taskid` varchar(200) NOT NULL,                PRIMARY KEY (`taskid`)            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='联麓任务id去重表'";        db_query($llsms_taskid_sql);        $get_llsms_taskid = db_get('yx_000_llsms_taskid',['taskid' => $bohui_taskid]);        if(!empty($get_llsms_taskid)){            return_json('201','已发送过');        }        $insert_llsms_taskid = $insertid = db_insert('yx_000_llsms_taskid', ['taskid' => $bohui_taskid]);        if (empty($insert_llsms_taskid)) {            return_json('201','已发送过');        }        $log = db_getall(t_sms_send_log, array('tradeId' => $bohui_taskid,'status !='=>1, 'templateKey' => 'notify'), array('mobile', 'content', 'fixed_time', 'templateKey','themeid'));        if (empty($log)) {            return_json('201','未查询到该短信');        }        $mobile_arr = array_column($log, 'mobile');        $qianming = '【' . self::getSignature($system,$log["themeid"]) . '】';        $content = $log[0]['content'];        $is_keywords = (substr($content, strpos($content, '。')) === '。') ? true : false; //判断是否以下划线结尾        if ($is_keywords) {            $content .= '拒收请回复R';        } else {            $sms_num1 = ceil(mb_strlen($qianming . $content, 'UTF8') / 67);            $sms_num2 = ceil(mb_strlen($qianming . $content . '。拒收请回复R', 'UTF8') / 67);            if ($sms_num1 === $sms_num2) {                $content .= '。拒收请回复R';            } else {                $content .= '拒收请回复R';            }        }        if (!empty($log[0]['fixed_time'])) {            $fixed_time = $log[0]['fixed_time'];        }        $tag = MODULE_NAME.'-'.$themeid;        $res = Sms::llNormalSend($mobile_arr, $qianming, $content, $fixed_time, $tag, 'sales');        if ($res['msg'] == 'success') {            $TaskId = $res['data']['taskId'];            $update = ['tradeId' => $TaskId, 'content' => $content, 'templateKey' => 'sales','status'=>6];            $res_y = db_update(t_sms_send_log,$update, array('tradeId' => $bohui_taskid));            //修改失败后重试三次            if (empty($res_y)) {                for ($i = 1; $i <= 3; $i++) {                    $res_y1 = db_update(t_sms_send_log,$update, array('tradeId' => $bohui_taskid));                    if (!empty($res_y1)) {                        break;                    }                    if ($i == 3) {                        yxlog($TaskId, '短信发送，但写入tradeId失败！');                        return_json('201','短信发送，但写入tradeId失败');                    }                }            }            yxlog($TaskId, '普通短信转营销短信发送成功');            return_json('200','成功');        } else {            yxlog('', '普通短信转营销短信请求接口失败');            return_json('201','失败');        }    }    public static function getSignature($system,$themeid=0)    {        $text = mb_substr($_G['companyname'],0,2);        if($themeid<=0){            $themeid = Theme::getDefaultThemenew();        }        $theme = Theme::getThemeById($themeid);//        $theme['laoshi'] = '策划：广润-金泉';        if(strpos($theme['laoshi'], "广润")){            $text = '慧车网';        }        return $text;    }}